关于Python super()的理解

参考资料:Python super() 函数 和object的理解

参考资料: ​​​​​​super的理解和使用

  • 需要知道 super 是一个类,调用super()相当于创建一个对象。
  • 在Python中,每个类都有一个mro的类方法,返回的是一个祖先类的列表。(MRO(method resolution order):表示了类继承体系中的成员解析顺序。)
class Root():
    def __init__(self):
        print("this is Root")


class B(Root):
    def __init__(self):
        print("---> enter B")
        
        # super(B, self).__init__()
        
        # 等效与:
        temp = super(B,self)
        temp.__init__()
        
        print('temp is B type?',isinstance(temp,B))
        print('temp is Root type?',isinstance(temp,Root))
        print('temp is super type?',isinstance(temp,super))
        
        print("<--- leave B")


b = B()
print('MRO of b :',b.__class__.__mro__)

输出如下: 

---> enter B
this is Root
temp is B type? False
temp is Root type? False
temp is super type? True
<--- leave B
MRO of b : (<class '__main__.B'>, <class '__main__.Root'>, <class 'object'>)
  • Python3的类(类默认继承了object——新式类)默认按照“广度优先”搜索父类的方法(而Python2中未继承object类的类称为经典类,经典类默认按照“深度优先”搜索父类的方法)
class A:
    def f(self):
        print('A')
        super(A, self).f()

class B(A):
    def f(self):
        print('B')
        super(B, self).f()
        
class C(A):
    def f(self):
        print('C')
        super(C, self).f()

class X:
    def f(self):
        print('X')

class Y(X):
    def f(self):
        print('Y')
        super(Y, self).f()

class Foo(B,C,Y):
    pass

foo = Foo()
foo.f()

Python3 按照“广度优先”搜索,输出如下:

B
C
A
Y
X

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值