我无法让子类正常运行。实例化超类时,一切都按预期工作。但是子类中的吸气剂和制定者似乎没有做任何事情。
注释掉对超类__init__
函数的调用没有任何效果,就好像它甚至不存在一样。
class Animal:
__name = None
__sound = 0
def __init__(self, name, sound):
self.__name = name
self.__sound = sound
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def get_sound(self):
return self.__sound
def get_type(self):
return "Animal"
def toString(self):
return "{} says {}".format(self.__name, self.__sound)
class Dog(Animal):
__owner = None
def __init__(self, name, sound, owner):
super().__init__(name, sound)
self.__owner = owner
def set_owner(self, owner):
self.__owner = owner
def get_owner(self):
return self.__owner
def get_type(self):
return "Dog"
def toString(self):
return "{} says {} and his owner is {}".format(self.__name, self.__sound, self.__owner)
cat = Animal('Whiskers', 'Meow')
print(cat.toString())
spot = Dog("Spot", "Borf!", "Derek")
spot.set_name = "Spot?"
spot.set_owner = "Brad"
print(spot.get_type())
print(spot.get_name())
print(spot.get_owner())
print(spot.toString())
print(spot.multiple_sounds(howmany=4))
给定的输出如下:
Whiskers says Meow
Dog
Spot
Derek
Traceback (most recent call last):
File "./hellopython.py", line 245, in <module>
print(spot.toString())
File "./hellopython.py", line 228, in toString
return "{} says {} and his owner is {}".format(self.__name, self.__sound, self.__owner)
AttributeError: 'Dog' object has no attribute '_Dog__name'
我不明白,因为我希望更改名称和所有者。为什么不能在超类init函数之外获取或设置任何东西?我正在使用python 3,关于这个主题的其他帖子建议将类中的参数设置为super(仅限python 2,尝试过它并且仍然无法工作)。为什么在这种情况下无法访问属性?