gpt4 book ai didi

使用 super() 时不调用 Python 多重继承构造函数

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:48 25 4
gpt4 key购买 nike

考虑以下代码:

class A(object):
def __init__(self):
pass
class B(object):
def __init__(self):
self.something = 'blue'
def get_something(self):
return self.something
class C(A,B):
def __init__(self):
super().__init__()
print(self.get_something())

然后做:

c = C()

结果是这样的:

AttributeError: 'C' object has no attribute 'something'

我想这是因为在使用 super() 时没有调用 B 的构造函数。有没有办法用 Python 3 实现正确的行为?

最佳答案

如果子类使用 super,则父类(super class)应该使用 super。如果将 super().__init__() 行添加到 A 和 B 中,您的示例应该再次运行。

检查C:的方法解析顺序

>>> C.mro()
[__main__.C, __main__.A, __main__.B, builtins.object]

This article应该把事情弄清楚。

关于使用 super() 时不调用 Python 多重继承构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25372653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com