栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

关于Python super()的理解

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于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 : (, , )
  • 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1034806.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号