1. The use of super ()
class Master(object) :
def __init__(self) :
self.kongfu = "Recipe for ancient Pancake Fruit." # Instance variables, attributes
def make_cake(self) : # instance method, method
print("[ancient method] according to <%s> made a pancake fruit..." % self.kongfu)
The parent class is Master
class School(Master) :
def __init__(self) :
self.kongfu = "Modern pancake recipe"
def make_cake(self) :
print("[Hyundai] made a pancake according to <%s>..." % self.kongfu)
super().__init__() Execute the constructor of the parent class
super().make_cake() Execute the instance method of the parent class
The parent classes are School and Master
class Prentice(School, Master) : # multiple inheritance, inheriting multiple parent classes
def __init__(self) :
self.kongfu = "Cat's Pancake Recipe"
def make_cake(self) :
self.__init__() Self. Kongfu = "...."
print("[Cat's] made a pancake according to <%s>..." % self.kongfu)
def make_all_cake(self) :
# method 1. Specify the method to execute the parent class (code bloat)
# School.__init__(self)
# School.make_cake(self)
#
# Master.__init__(self)
# Master.make_cake(self)
#
# self.__init__()
# self.make_cake()
# method 2.super () with argument version, only support the new class
# super (Prentice, self) __init__ () # parent __init__ method
# super(Prentice, self).make_cake()
# self.make_cake()
A simplified version of method 3.super (), which supports only new classes
super().__init__() # Execute the __init__ method of the parent class
super().make_cake() Execute the instance method of the parent class
self.make_cake() Execute instance methods of this class
damao = Prentice()
damao.make_cake()
damao.make_all_cake()
# print(Prentice.__mro__)
Copy the code
Knowledge:
A subclass inherits more than one parent class, and if the parent class name changes, the subclass changes more than one time. And the need to repeatedly write multiple calls, appears bloated code.
With super(), you can call all the parent methods one by one and only do it once. The call order follows the order of mrO class attributes.
Note: If multiple parent classes are inherited and each parent class has a method of the same name, only the first parent class is executed by default (methods of the same name are executed only once, currently super() does not support executing multiple parent methods of the same name)
Super () is a post-Python 2.3 mechanism for multi-level inheritance that is usually single inheritance.