Python继承返回属性错误
刚开始学习Python,我是Derek Banas的粉丝,一直在学习一个教程,我被一些代码困住了Python继承返回属性错误,python,inheritance,Python,Inheritance,刚开始学习Python,我是Derek Banas的粉丝,一直在学习一个教程,我被一些代码困住了 class Dog(Animal): __owner = "" def __init__(self, name, height, weight, sound, owner): self.__owner = owner super(Dog, self).__init__(name, height, weight, sound) def set
class Dog(Animal):
__owner = ""
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super(Dog, self).__init__(name, height, weight, sound)
def set_owner(self, owner):
self.__owner = owner
def get_owner(self):
return self.__owner
def get_type(self):
print("Dog")
def tostring(self):
return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner)
def multiple_sounds(self, how_many=None):
if how_many is None:
print(self.get_sound())
else:
print(self.get_sound() * how_many)
spot = Dog("Spot", 53, 27, "Ruff", "Seb")
print(spot.tostring())
我收到了以下错误:
Traceback (most recent call last):
File "G:/JetBrains/PyCharm Community Edition 4.5.4/PyCharm Projects/Testing 123/testing objects.py", line 87, in <module>
print(spot.tostring())
File "G:/JetBrains/PyCharm Community Edition 4.5.4/PyCharm Projects/Testing 123/testing objects.py", line 73, in tostring
return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
AttributeError: 'Dog' object has no attribute '_Dog__name'
您的
Animal
类正在使用。从-
由于类私有成员有一个有效的用例(即避免名称与子类定义的名称发生名称冲突),因此对这种称为名称混乱的机制的支持有限格式\uuu spam
的任何标识符(至少两个前导下划线,最多一个尾随下划线)以文本形式替换为\u classname\uuu spam
,其中classname是带前导下划线的当前类名
(强调矿山)
因此,在定义了动物
类后,任何名称(如\u名称
)都将更改为\u动物\u名称
)等。您还需要像在狗
类中一样访问它们
但是我认为实际上不需要使用名称损坏,如果您不是有意要使用名称损坏,那么应该避免使用两个前导下划线。子类本身没有该属性,请使用该属性
return super(Dog, self).toString() + "His owner is {}".format(self.__owner)
更改您的功能代码 来自
def toString(self):
return "{} is {} cm tall and {} kilograms and say {} and the owner is {}".format(
self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner)
def toString(self):
return "{} is {} cm tall and {} kilograms and say {} and the owner is {}".format(
self.get_name(),
self.get_height(),
self.get_weight(),
self.get_sound(),
self.get_owner())
至
def toString(self):
return "{} is {} cm tall and {} kilograms and say {} and the owner is {}".format(
self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner)
def toString(self):
return "{} is {} cm tall and {} kilograms and say {} and the owner is {}".format(
self.get_name(),
self.get_height(),
self.get_weight(),
self.get_sound(),
self.get_owner())
由于名称是在super中设置的,因此我们可能需要查看
动物
代码。顺便说一句,创建tostring()
方法不是pythonic方法,因为您可能想看看重写\uuuu str\uuuuu
和\uuuu repr\uuuuu
魔术方法。这是真的,我不确定是否有必要,如果我说的是它试图查找的属性已经存在于它的继承的超链接中,但是我会在原始帖子中添加动物类代码。如果你是从教程中得到的,你应该马上得到另一个。这完全不是Pythonic代码。简而言之:使用一个尾随下划线,而不是双下划线。谢谢,这似乎奏效了。这个名字是不是在去年就被引入了?我这样问是因为在我看的教程中,他们在使用2个下划线作为属性时没有任何问题。嗨@Simon Neubauer,你能给你的答案添加一些解释吗?