为什么这个简单的代码不适用于 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的回答 - 尽量避免对私有(private)变量使用双下划线
__。它不是 Python 方式(代码风格)。 See the discussion for more info here .
请您参考如下方法:
您有 2 个问题:
您错误地命名了
Mechanism的__init__方法;你缺少两个下划线。您的
__init__方法在多重继承情况下无法正确协作。确保始终在 所有__init__方法中调用super(...).__init__()。
以下代码有效:
class Mechanism(object):
def __init__(self):
super(Mechanism, self).__init__()
print('Init Mechanism')
self.__mechanism = 'this is mechanism'
def get_mechanism(self):
return self.__mechanism
class Vehicle(object):
def __init__(self):
super(Vehicle, self).__init__()
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()
Init Vehicle
Init Mechanism
>>> print(c.get_mechanism())
this is mechanism
>>> print(c.get_vehicle())
this is vehicle
您或许还应该不使用双下划线名称。参见 Inheritance of private and protected methods in Python有关详细信息,但简短的原因是您在这里没有类私有(private)名称的用例,因为您没有构建旨在由第三方扩展的框架;这是此类名称的唯一实际用例。
坚持使用单下划线名称,例如 _mechanism 和 _vehicle。
