【问题标题】:Calling __init__ of all parent class with different parameters [duplicate]使用不同参数调用所有父类的 __init__ [重复]
【发布时间】:2020-04-24 16:17:44
【问题描述】:

我有一些这样的类结构:

class A:
    def __init__(self):
        print("A")
class B:
    def __init__(self, x):
        print("B")

class C(A,B):
    def __init__(self):
        super(C, self).__init__() # ???

c=C()

如您所见,AB 都是 C 的父类。我想在C__init__ 中调用这两个类__init__。我想将一些参数传递给 B 的__init__。有什么办法可以用super 关键字来做到这一点?我认为这会奏效:

class C(A,B):
    def __init__(self):
        A.__init__()
        B.__init__(5)

我们应该这样直接调用__init__,还是有更好的解决方案?

【问题讨论】:

  • 协作超级调用的前提是所有继承的方法在整个层次结构中都具有兼容的签名。如果您只对实现重用感兴趣,那么组合/委托可能是比多重继承更好的设计选择(取决于上下文等)。

标签: python python-3.x oop multiple-inheritance


【解决方案1】:

您必须将 self 作为参数提供给父类的 __init__()。

class C(A,B):
def __init__(self):
    A.__init__(self)
    B.__init__(self, 5)

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 2010-11-26
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多