Python Subclass Inheritance of Parent Class Constructor Explanation
Category Programming Techniques
If the subclass needs the constructor method of the parent class, it is necessary to explicitly call the constructor of the parent class, or not to override the constructor of the parent class.
If the subclass does not override the __init__
, when instantiating the subclass, the __init__
defined by the parent class will be automatically called.
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('tutorialpro')
print(son.getName())
Output result:
name: tutorialpro
Son tutorialpro
If the __init__
is overridden, when instantiating the subclass, the __init__
already defined by the parent class will not be called. The syntax 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('tutorialpro')
print(son.getName())
Output result:
hi
Son tutorialpro
If the __init__
is overridden and the constructor method of the parent class needs to be inherited, the super
keyword can be used:
super(Subclass, self).__init__(argument1, argument2, ...)
There is also a classic way of writing:
ParentClass.__init__(self, argument1, argument2, ...)
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('tutorialpro')
print(son.getName())
Output result:
name: tutorialpro
hi
Son tutorialpro
#
-
** dengjianxiong
* 121**[email protected]
Scenario one: Subclass needs to automatically call the parent class method: If the subclass does not override the __init__()
method, the parent class's __init__()
method will be automatically called after instantiating the subclass.
Scenario two: Subclass does not need to automatically call the parent class method: If the subclass overrides the __init__()
method, the parent class's __init__()
method will not be automatically called after instantiating the subclass.
Scenario three: Subclass overrides the __init__()
method and also needs to call the parent class method: Use the super
keyword:
super(Subclass, self).__init__(argument1, argument2, ...)
class Son(Father):
def __init__(self, name):
super(Son, self).__init__(name)
** dengjianxiong
* 121**[email protected]
** Click to share notes
-
-
-