【问题标题】:Python 3 multiple inheritance __init__ second class [duplicate]Python 3多重继承__init__第二类[重复]
【发布时间】:2019-10-06 08:43:35
【问题描述】:

在 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 构造函数? 是否可以用super从C类调用B构造函数?

【问题讨论】:

    标签: python initialization multiple-inheritance


    【解决方案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()
    
    

    【讨论】:

      猜你喜欢
      • 2020-04-28
      • 2013-05-26
      • 1970-01-01
      • 2020-07-05
      • 2021-11-28
      • 2012-01-31
      • 2018-06-13
      • 1970-01-01
      • 2011-09-26
      相关资源
      最近更新 更多