Python subclass calls the parent class method, and python calls the Class Method
During Python inheritance, if the subclass overrides the init () function, the init () of the parent class will not be called. In this case, if the subclass only wants () it is inconvenient to extend functions simply. Is there a convenient way to call the parent class from the subclass?
The first is to directly use the class name of the parent class for direct calls. (Python3.3)
class Parent: def __init__(self): print('This is parent init.') def sleep(self): print("Parent sleeps.") class Child(Parent): def __init__(self): Parent.__init__(self) print('This is child init.') def sleep(self): print("Child sleeps.") c=Child()
The second is to use super (type, obj ). methodName (args) is called. The first parameter indicates the class from which the parent class is located (excluding its own), and the second parameter indicates the class instance (generally using self ), the parameter args is not written when the parameter of the parent class method is only self.
class Parent: def __init__(self): print('This is parent init.') def sleep(self): print("Parent sleeps.") class Child(Parent): def __init__(self): #Parent.__init__(self) super(Child,self).__init__() print('This is child init.') def sleep(self): print("Child sleeps.") c=Child()
When used inside a class, type and obj in super (type, obj). methodName (args) can be omitted without writing.
In addition, you can use this function outside the class. For example, if a subclass overwrites a method of the parent class, you want to call this method of the parent class through the subclass object:
class Parent: def __init__(self): print('This is parent init.') def sleep(self): print("Parent sleeps.") class Child(Parent): def __init__(self): #Parent.__init__(self) super().__init__() print('This is child init.') def sleep(self): print("Child sleeps.") c=Child() c.sleep() super(Child,c).sleep()