When learning Python classes, you will encounter a function like init() in the class, which is actually the construction method of Python.
The construction method is similar to the initialization method like init() to initialize the state of the newly created object. It will be called immediately after an object is created, such as instantiating a class:
f = FooBar()
f.init()#Manual initialization
It can be simplified into the following form by using the construction method: the magic method init() is automatically called after the object is created to initialize the object
f = FooBar()
After understanding the construction method, come to an advanced question, that is, the problem that the initial value in the construction method of the parent class cannot be inherited.
classBird:
def __init__(self):
self.hungry = True
def eat(self):if self.hungry:
print 'Ahahahah'else:
print 'No thanks!'classSongBird(Bird):
def __init__(self):
self.sound ='Squawk'
def sing(self):
print self.song()
sb =SongBird()
sb.sing() #Can output normally
sb.eat() #Report an error because there is no hungry feature in songgird
There are two ways to solve this problem:
classSongBird(Bird):
def __init__(self):
Bird.__init__(self) #
self.sound ='Squawk'
def sing(self):
print self.song()
Principle: When the method of an instance is called, the self parameter of the method will be automatically bound to the instance (called the binding method); if the method of the class (such as Bird.init) is called directly, then no instance will be Binding, you can freely provide the required self parameter (unbound method).
classSongBird(Bird):
def __init__(self):super(SongBird,self).__init__()
self.sound ='Squawk'
def sing(self):
print self.song()
Principle: It will find all superclasses and superclasses of superclasses until it finds the required characteristics.
The super() function is a method used to call the parent class (super class).
super is used to solve the problem of multiple inheritance. It is okay to directly call the parent class method with the class name when using single inheritance, but if you use multiple inheritance, it will involve the search order (MRO) and re
Recall (diamond inheritance) and other issues.
MRO is the method resolution sequence table of the class, in fact, it is the sequence table when inheriting the methods of the parent class. (Novice Document)
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts