1、 If you need the constructor of the parent class in the subclass, you need to call the constructor of the parent class , Or do not override the constructor of the parent class .
Subclasses do not override init, When instantiating a subclass , Will automatically call the parent class definition init.
class Father(object): # All parent classes inherit by default object class , Write but not write https://blog.csdn.net/txnuli/article/details/110862361
def __init__(self, name):
self.name = name # self It refers to itself , there self Is the class itself ,self.name Is the variable in the class , yes Father all .
print(f"name:{
self.name}")
def getName(self):
return 'Father ' + self.name
class Son(Father):
def getName(self):
return 'Son ' + self.name
if __name__ == '__main__':
son = Son('yaya')
print(son.getName())
The output is :
name:yaya
Son yaya
2、 rewrite __init__ when , Instantiate subclasses , Will not call the parent class already defined init,
The syntax is as follows :
class Father(object):
def __init__(self, name):
self.name = name # self It refers to itself , there self Is the class itself ,self.name Is the variable in the class , yes Father all .
print(f"name:{
self.name}")
def getName(self):
return 'Father ' + self.name
class Son(Father):
def __init__(self, name):
self.name = name
print('hi')
def getName(self):
return 'Son ' + self.name
if __name__ == '__main__':
son = Son('yaya')
print(son.getName())
The output is :
hi
Son yaya
3、 rewrite __init__ when , To inherit the construction method of the parent class , have access to super keyword :
super( Subclass ,self).__init__( Parameters 1, Parameters 2,....)
or
Parent class name .__init__(self, Parameters 1, Parameters 2,...)
class Father(object):
def __init__(self, name):
self.name = name # self It refers to itself , there self Is the class itself ,self.name Is the variable in the class , yes Father all .
print(f"name:{
self.name}")
def getName(self):
return 'Father ' + self.name
class Son(Father):
def __init__(self, name):
self.name = name
print('hi')
super().__init__(name)
def getName(self):
return 'Son ' + self.name
if __name__ == '__main__':
son = Son('yaya')
print(son.getName())
The output is :
hi
name:yaya
Son yaya
summary :
One : The subclass calls the method of the parent class : Subclasses do not override __init__() Method , After instantiating subclasses , Will call the parent class automatically __init__() Methods .
Two : Subclasses do not need to automatically call the methods of the parent class : Subclass rewriting __init__() Method , After instantiating subclasses , The of the parent class will not be called automatically __init__() Methods .
3、 ... and : Subclass rewriting __init__() Method needs to call the method of the parent class : Use super key word