Python super()

1.描述

super() 用于调用父类。

super() 用来解决多重继承,直接用类名调用父类方法在单继承的时候是没有问题,但在多继承上,涉及查找顺序、重复调用等问题。

MRO 是类的方法解析顺序表,其实也是继承父类方法时的顺序表。


2.语法

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

参数:

type:类

object-or-type:类,一般是 self

实例:

super() 或 super(B, self):首先找到 B 的父类 A,然后把 B 类的对象转换为 A 类的对象。

class A:
    def __add__(self, x):
        y = x+1
        print(y)

class B(A):
    def __add__(self, x):
        super().__add__(x)

b = B()
b.__add__(2) 

输出:

3

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % message)
 
class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        super(FooChild,self).__init__()    
        print ('Child')
        
    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction')
        print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

输出:

Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.
posted @ 2021-08-27 10:22  做梦当财神  阅读(69)  评论(0编辑  收藏  举报