您如何从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
如何使此代码正确运行? 那么,如何从类“第三”类的类“第三”,第二和第二2个变量继承,并添加一个变量“ D”?
I have a diamond structure of classes in Python and I need to inherit the variables of the three superclasses in the last one.
This is an example of this problem :
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
by compiling this example I don't obtain any errors, but if i try to create an istance of the third class like this :
a = 1
b = 2
c = 3
Q = 4
d = 5
t = third(a, b, c, Q, d)
I receive this error :
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
How can i make this code run correctly ?
So how can I inherit from class "third" the variables of the classes Base, second and second2 and add one variables "d" ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,我会避免使用
super()
,因为您的 init ()定义甚至没有相同数量的args,这是您的可能原因问题。但是,您最终将其基本的初始化被称为两次,这不是您通常想要的。希望有帮助。
I'd avoid using
super()
in this case, as your init() definitions don't even have the same number of args, this being a possible cause to your issue. However, you'll end up with your Base init being called twice, which is not something you'd generally want.Hope that helps.