python super原理,不是指父类

复制代码
class a(object):
    def __init__(self):
        print('in a')
class b(a):
    def __init__(self):
        print('in b')
        super().__init__()
        print('out b')
class c(a):
    def __init__(self):
        print('in c')
        super().__init__()
        print('out c')

class d(b, c):
    def __init__(self):
        print('in d')
        super().__init__()
        print('out d')

a = d()
print(a.__class__.mro())
复制代码

每个对象都有个属性__class__.mro()

mro是method resolve order的缩写

代码中是写的super().__init__()

super()这种写法是super(当前类名,self)的简写

 

然后我们直接来看看这段代码执行的结果

复制代码
[Running] python "d:\pyqt5\signal.py"
in d
in b
in c
in a
out c
out b
out d
(<class '__main__.d'>, <class '__main__.b'>, <class '__main__.c'>, <class '__main__.a'>, <class 'object'>)
复制代码

为啥中间会输出c?

c并不是b的父类啊

super其实干的是下面这件事

def super(cls, inst):
    mro = inst.__class__.mro()
    return mro[mro.index(cls) + 1]

就是在mro列表中去找下一个类,所以会产生这种输出

posted @   君莫笑hhhhhh  阅读(207)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示