Python basic grammar (miscellaneous) Memo (4)

2.7 base. It is a prerequisite that you know some other language.

Relation

Modules and classes

from import Declaration "Use Decimal class from standard module called decimal"

>>> from decimal import Decimal

Import all classes
>>> d = Decimal(10)
>>> print d
10

>>> print d + 3  #Decimal class+Has a method corresponding to the operator
13

For more information about Decimal http://docs.python.jp/2/library/decimal.html

Class definition

>>> class MyClass:
...	    pass
...
>>> mc = MyClass()
>>> print mc
<__main__.MyClass instance at 0x1076245a8>

Class names are usually written in camel case. pass is a Null Operation and does nothing.

attribute

Python does not have the ability to write member variable definitions along with class definitions. Attributes (data members) are defined for each instance by assigning them to variables separated by dots for the created instance.

>>> mc = MyClass()
>>> mc.value = 10
>>> print(mc.value)
10

>>> mc2 = MyClass()
>>> print mc2.value
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute 'value'

Method definition and \ __ init__

\ Init (and \ __ new__) are provided as constructor-like initialization methods.

class MyClass:
    #Initialization method
    def __init__(self):
        self.h = 'hoge'   #Add attributes
        
    #Method
    def print_h(self):
        print h
        
mc = MyClass()
mc.print_h()  # => 'hoge'

The instance object itself is passed to the first argument, self. It is customary to use self, but this and me also work. If you want to give a variable at initialization

class Rect:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        
    def area(self):
        return self.width * self.height
        
r = Rect(100, 50)
print r.height  # => 50
print r.area    # => 5000

become that way. Note that the caller of the initialization method ignores the first argument. If you forget self as an argument,

>>> class MyClass():
...     def hoge():
...         print 'hoge'
...
>>> mc = MyClass()
>>> mc.hoge()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: hoge() takes no arguments (1 given)

Will result in the error.

Encapsulation

There are no private keywords in python, and if you want to hide an attribute or method name, put an underscore (one or two) in front of it.

def _private_method():
    # ....
    
def __secret_method():
    # ....

In one case, it is customary to express the intention to "don't call from the outside", and in the two cases, the name is automatically changed internally to make it uncallable from the outside.

class MyClass:
    def __init__(self, size):
        self._size = size
        self.__size = size

mc = MyClass(100)
print mc._size    # => 100
print mc.__size   # => AttributeError

Class inheritance

Python supports ** multiple inheritance **. You can also create new classes by inheriting built-in types such as numbers and strings.

Definition

class (superclass name [, superclass 2, superclass 3,,]):

It seems that the behavior is slightly different when the inherited class is not specified and when object is inherited. It is recommended to inherit object if it does not inherit anything (?).

In Python3, it seems that object will be inherited by default if the parent class is not specified.

class C1(): 
    pass
print dir(C1) #=> ['__doc__', '__module__']

class C2(object): 
    pass
print dir(C2) #=> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']

Override and super

class Rectangle(object):
    def __init__(self, w, h):
        self.w = w
        self.h = h
        self.color = 'red'
  
    def area(self):
        return self.w * self.h
      
      
class Square(Rectangle):     
    #Redefine (override) initialization method
    def __init__(self, length):
        self.w = self.h = length

s = Square(100)
print s.area()   #=>10000, parent class method call

Method overriding is a complete overriding, and it doesn't act like calling the parent's constructor automatically. So, for example, the variable color initialized by the parent class \ __ init__ () above does not exist in the Square class instance. To prevent that, call the parent method with super (),

class Square(Rectangle):
    def __init__(self, length):
        super(Square, self).__init__(length, length)

I have to call it awkward. Identify the parent class by passing your type and self. Also, at this time, if the parent class does not inherit the object class, an error will occur.

In Python3, it seems that you can get a superclass with just super ().

Recommended Posts

Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Python basic grammar (miscellaneous) Memo (4)
Python basic grammar (miscellaneous)
Python basic grammar memo
Python Basic Grammar Memo (Part 1)
Python3 basic grammar
Python basic grammar / algorithm
Python basic memo --Part 2
Basic Python command memo
Python basic grammar note (4)
Python basic grammar note (3)
Python basic memo --Part 1
Basic Python 3 grammar (some Python iterations)
Python installation and basic grammar
Basic Python grammar for beginners
Python (Python 3.7.7) installation and basic grammar
Python memo
python memo
Python memo
Python memo
Python memo
Python memo
Java and Python basic grammar comparison
Basic grammar of Python3 system (dictionary)
[Python] Memo dictionary
RF Python Basic_01
python beginner memo (9.2-10)
python grammar check
python beginner memo (9.1)
Flask basic memo
Basic Python writing
★ Memo ★ Python Iroha
[Basic grammar] Differences between Ruby / Python / PHP
[Python] EDA memo
Python 3 operator memo
Python grammar notes
[Python] I personally summarized the basic grammar.
Basic grammar of Python3 system (character string)
Basic grammar of Python3 series (list, tuple)
[My memo] python
Python3 metaclass memo
RF Python Basic_02
[Python] Basemap memo
Basic grammar of Python3 system (included notation)
Python beginner memo (2)
[Python] Numpy memo
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Memo # 1 for Python beginners to read "Detailed Python Grammar"
VBA user tried using Python / R: basic grammar
Memo # 2 for Python beginners to read "Detailed Python Grammar"
Memo # 7 for Python beginners to read "Detailed Python Grammar"
Memo # 6 for Python beginners to read "Detailed Python Grammar"
Memo # 5 for Python beginners to read "Detailed Python Grammar"
[Go] Basic grammar ① Definition
Python basic course (12 functions)
Python I'm also basic
Python class (Python learning memo ⑦)
My python environment memo
Python Basic Course (7 Dictionary)
python openCV installation (memo)