If the parent class constructor is needed in a subclass, you must explicitly call the parent class constructor, or do not override the parent class constructor.
Subclass does not override__init__, when instantiating a subclass, it will automatically call the parent class's defined__init__。
Example
class Father(object):
def __init__(self, name):
self.name=name
print ( "name: %s" %( self.name) )
def getName(self):
return 'Father ' + self.name
class Son(Father):
def getName(self):
return 'Son '+self.name
if __name__=='__main__':
son=Son('example')
print ( son.getName() )
The output result is:
name: example Son example
If you override__init__, when instantiating the subclass, it will not call the parent class's already defined__init__, the syntax format is as follows:
Example
class Father(object):
def __init__(self, name):
self.name=name
print ( "name: %s" %( self.name) )
def getName(self):
return 'Father ' + self.name
class Son(Father):
def __init__(self, name):
print ( "hi" )
self.name = name
def getName(self):
return 'Son '+self.name
if __name__=='__main__':
son=Son('example')
print ( son.getName() )
The output result is:
hi Son example
If you override__init__, to inherit the parent class constructor, you can usesuperkeyword:
super(子类,self).__init__(参数1,参数2,....)
There is also a classic way to write it:
父类名称.__init__(self,参数1,参数2,...)
Example
class Father(object):
def __init__(self, name):
self.name=name
print ( "name: %s" %( self.name))
def getName(self):
return 'Father ' + self.name
class Son(Father):
def __init__(self, name):
super(Son, self).__init__(name)
print ("hi")
self.name = name
def getName(self):
return 'Son '+self.name
if __name__=='__main__':
son=Son('example')
print ( son.getName() )
The output result is:
name: example hi Son example