美文网首页
Python Mixin多继承和super()

Python Mixin多继承和super()

作者: 霡霂976447044 | 来源:发表于2021-08-02 16:24 被阅读0次
class A(object):
    def __init__(self):
        # super(A, self).__init__()
        print('aaa')


class B(object):
    def __init__(self):
        # super(B, self).__init__()
        print('bbb')


class Son(A, B):
    pass


print(Son.mro())

Son()

多继承,Son会调用mro最近的A的__init__方法。如果在A中没有调用super(A, self).__init__()那么是不会执行B的__init__

[<class '__main__.Son'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
aaa

在mixin中如果要调用另一个父类的逻辑,就需要使用super()

相关文章

网友评论

      本文标题:Python Mixin多继承和super()

      本文链接:https://www.haomeiwen.com/subject/zxljvltx.html