Python 3多重继承__init__第二类[重复]

问题描述 投票:0回答:1

此问题已经在这里有了答案:

在Python3中,我有一个继承其他两个类的类。但是,正如我看到的,当初始化一个对象时,仅初始化它的第一类也请参见示例...

    class A:
        def __init__(self):
            print("A constructor")


    class B:
        def __init__(self):
            print("B constructor")


    class C(A, B):
        def __init__(self):
            print("C constructor")
            super().__init__()


    c = C()

这具有输出:

C构造函数构造函数

我的问题是,为什么它也不调用B构造函数?是否可以通过C类的super调用B构造函数?

python initialization multiple-inheritance
1个回答
1
投票
class A:
    def __init__(self):
        print("A constructor")
        super().__init__()        # We need to explicitly call super's __init__ method. Otherwise, None will be returned and the execution will be stopped here.

class B:
    def __init__(self):
        print("B constructor")


class C(A, B):
    def __init__(self):
        print("C constructor")
        super().__init__()        # This will call class A's __init__ method. Try: print(C.mro()) to know why it will call A's __init__ method and not B's.

c = C()

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.