考虑以下代码:
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())
然后做:
^{pr2}$结果是这样的:
AttributeError: 'C' object has no attribute 'something'
我想这是因为在使用super()时没有调用B的构造函数。有没有一种方法可以用python3实现正确的行为?在
如果子类使用super,超类应该使用super。如果您将
super().__init__()
行添加到A和B中,您的示例应该可以再次运行。在检查C的方法解析顺序:
This article应该把事情弄清楚。在
正如其他人所提到的,方法解析顺序在这里是关键。如果要调用多个超类构造函数,则必须直接调用它们。在
相关问题 更多 >
编程相关推荐