【发布时间】:2017-12-18 18:05:22
【问题描述】:
为什么这个简单的代码不适用于 Python 2.7?请帮忙。很可能我在类的“新样式”中滥用super 方法。
class Mechanism(object):
def __init__(self):
print('Init Mechanism')
self.__mechanism = 'this is mechanism'
def get_mechanism(self):
return self.__mechanism
class Vehicle(object):
def __init__(self):
print('Init Vehicle')
self.__vehicle = 'this is vehicle'
def get_vehicle(self):
return self.__vehicle
class Car(Mechanism, Vehicle):
def __init__(self):
super(Car, self).__init__()
c = Car()
print(c.get_mechanism())
print(c.get_vehicle())
错误:
Init Vehicle
Traceback (most recent call last):
File "check_inheritance.py", line 22, in <module>
print(c.get_mechanism())
File "check_inheritance.py", line 7, in get_mechanism
return self.__mechanism
AttributeError: 'Car' object has no attribute '_Mechanism__mechanism'
编辑
- 将
Mechanism类中的def __init(self):固定到def __init__(self): - 正确答案是在所有类中使用
super方法。不仅在Car类中。见Martijn Pieters的回答 - 尽量避免对私有变量使用双下划线
__。它不是 Python 方式(代码风格)。 See the discussion for more info here。
【问题讨论】:
-
你的机制初始化拼写错误,前后应该有两个下划线
-
这里还误用了
super:按照目前的结构,Vehicle.__init__方法不会被调用。您需要一个公共根类(Vehicle和Mechanism的基类),所有子类,包括Vehicle和Mechanism都应该调用super。 -
@MartijnPieters:我认为除了拼写错误的
__init__方法之外,这里还有一个关于使用 super 的有效问题。 -
在这种情况下,您只是打错了字,并且您忘记调用链中的下一个
__init__方法,因此没有调用Mechanism的初始化程序有两个不同的原因。你真的不应该使用前导双下划线属性,除非你正在为第 3 方构建一个框架来扩展,请参阅Inheritance of private and protected methods in Python -
您必须在 所有 子类中调用
super才能使协作式多重继承正常工作。然后私有变量就可以正常工作了。
标签: python python-2.7 inheritance multiple-inheritance