Python3 depth understanding of super () function

Foreword

In-depth understanding of super () function in a derived class, if the re-definition of a method, which overrides the parent class method of the same name, but sometimes, at the same time we hope to realize the function of the parent class, then, we need to call a parent the class methods, may be () function is achieved by using super.

description

  • super () function is a method call the parent class (superclass) is used.
  • super is used to solve the problem of multiple inheritance, class name with no problem call the parent class method directly when using single inheritance, but if you use multiple inheritance, involves the search order (MRO), repeated calls (diamond inheritance) and various other problem.
  • MRO is the way class resolution order table, in fact, is the inheritance order table when the parent class method.

grammar

super(type[, object-or-type])

parameter:

  • type - class.
  • object-or-type - based, generally self
class A:
    def __init__(self):
        print("A")


class B(A):
    def __init__(self):
        print("B")
        super().__init__()      # 调用父类


if __name__ == '__main__':
    b = B()

Output:

B
A			# super调用父类输出 A

Single inheritance

class Animal:  # 创建动物类
    """动物类"""

    def __init__(self, name):  # 初始化方法
        self.name = name

    def eat(self):  # 定义吃食物方法
        print('%s正在吃食物' % self.name)

    def play(self):  # 定义玩耍方法
        print('%s正在玩' % self.name)

    def sleep(self):  # 定义休息方法
        print('%s正在休息' % self.name)


class Dog(Animal):
    """狗类"""

    def __init__(self, name):
        super().__init__(name)              # 定义基类的初始化方法
        print('这是一只%s' % self.name)

    def eat(self):                          # 定义狗吃食物的方法
        print('%s正在吃狗粮' % self.name)

    def bark(self):                         # 定义狗叫的方法
        print('%s会汪汪叫' % self.name)


dog = Dog('哈士奇')                        # 创建动物类的实例
dog.eat()                                 # 调用吃食物的方法
dog.play()                                # 调用玩耍的方法
dog.bark()                                # 调用狗叫的方法

Output:

这是一只哈士奇
哈士奇正在吃狗粮
哈士奇正在玩
哈士奇会汪汪叫

The operation results of code line 21, as seen called Super (). The init () method, passing a parameter name. Animal __init__ method in the base class, the name assigned to self.name. So the first 22 lines of code will output "This is a husky."

Multi-inheritance

class Food:
    """实物类"""

    def __init__(self, name):
        print('%s是食物' % name)


class Vegetables(Food):
    """蔬菜类"""

    def __init__(self, Vname):
        print('%s是蔬菜' % Vname)
        super().__init__(Vname)


class Fruit(Food):
    """水果类"""

    def __init__(self, Fname):
        print('%s是水果' % Fname)
        super().__init__(Fname)


class Tomato(Fruit, Vegetables):
    """西红柿类"""
    def __init__(self):
        print('西红柿即是蔬菜又是水果')
        super().__init__('西红柿')


print(Tomato.__mro__)		# MRO 列表顺序
tomato = Tomato()           # 实例化西红柿类


Output:

(<class '__main__.Tomato'>, <class '__main__.Fruit'>, <class '__main__.Vegetables'>, <class '__main__.Food'>, <class 'object'>)
西红柿即是蔬菜又是水果
西红柿是水果
西红柿是蔬菜
西红柿是食物

According to operating results can be seen:

  • super function execution order is the order of the list MRO.
  • super () in fact and no substantive parent association, just like in the case of single inheritance, super () is just to get the parent class.
  • super () is equivalent to super (cls, inst) is obtained for a class list MRO inst cls class instance of.

to sum up

  • super () with no substantive parent association
  • super () is obtained for a class list MRO
Published 29 original articles · won praise 19 · views 1314

Guess you like

Origin blog.csdn.net/s1156605343/article/details/104695063