你怎么能继承变量从去年在Python类金刚石结构的吗?



我在Python中有一个菱形结构的类,我需要在最后一个继承三个超类的变量。下面是这个问题的一个例子:

class Base:
def __init__(self, a, b):
self.a = a
self.b = b
class second(Base):
def __init__(self, a, b, c):
super().__init__(a, b)
self.c = c
class second2(Base):
def __init__(self, a, b, Q):
super().__init__(a, b)
self.Q = Q
class third(second, second2):
def __init__(self, a, b, c, Q, d):
super().__init__(a, b, c, Q)
self.d = d

通过编译这个例子,我没有得到任何错误,但是如果我尝试像这样创建第三个类的实例:

a = 1
b = 2
c = 3
Q = 4
d = 5
t = third(a, b, c, Q, d)

我收到这个错误:

line 26, in <module>
t = third(a, b, c, Q, d)
line 18, in __init__
super().__init__(a, b, c, Q)
TypeError: second.__init__() takes 4 positional arguments but 5 were given

如何使这段代码运行正确?那么我如何从第三类继承呢?将类的变量Base、second和second2加1个变量">

?

在这种情况下,我会避免使用super(),因为您的init()定义甚至没有相同数量的参数,这可能是导致问题的原因。然而,你最终会得到Base init被调用两次,这通常不是你想要的。

class Base:
def __init__(self, a, b):
self.a = a
self.b = b
class second(Base):
def __init__(self, a, b, c):
Base.__init__(self, a, b)
self.c = c
class second2(Base):
def __init__(self, a, b, Q):
Base.__init__(self, a, b)
self.Q = Q
class third(second, second2):
def __init__(self, a, b, c, Q, d):
second.__init__(self, a, b, c)
second2.__init__(self, a, b, Q)
self.d = d

a = 1
b = 2
c = 3
Q = 4
d = 5
t = third(a, b, c, Q, d)
print(f"{t.a} {t.b} {t.c} {t.Q} {t.d}")

希望对你有帮助。

最新更新