In python, subclass inherits the _ init _ Method Instance of the parent class, and python _ init _
Preface
If you have written object-oriented code using Python __init__
The method is very familiar.,__init__
Method runs immediately when an object of the class is created. This method can be used to initialize your object.
Note:The start and end of the name are double underscores.
Parent Class
class A(object): def __init__(self, name): self.name=name print "name:", self.name def getName(self): return 'A ' + self.name
Subclass not override__init__
Automatically calls__init__
class B(A): def getName(self): return 'B '+self.name if __name__=='__main__': b=B('hello') print b.getName()
Run
$python lei2.py name: helloB hello
But it is rewritten.__init__
If the subclass is instantiated, the defined__init__
class A(object): def __init__(self, name): self.name=name print "name:", self.name def getName(self): return 'A ' + self.nameclass B(A): def __init__(self, name): print "hi" self.name = name def getName(self): return 'B '+self.nameif __name__=='__main__': b=B('hello') print b.getName()
Run
$python lei2.py hiB hello
In order to use or extend the behavior of the parent class, it is better to display the behavior that calls the parent class__init__
Method
class A(object): def __init__(self, name): self.name=name print "name:", self.name def getName(self): return 'A ' + self.nameclass B(A): def __init__(self, name): super(B, self).__init__(name) print "hi" self.name = name def getName(self): return 'B '+self.nameif __name__=='__main__': b=B('hello') print b.getName()
Run
$python lei2.pyname: hellohiB hello
Summary
The above is all about how python subclass inherits the _ init _ method of the parent class. I hope this article will help you in your learning or work, if you have any questions, you can leave a message.