我正在尝试使用继承自 Animal 类的 Dog 类来进行基本的 Python 继承。由于某种原因,我的 Dog 对象没有继承 name
正确,我不断得到 AttributeError: 'Dog' object has no attribute '_Dog__name'
。有谁知道会发生什么?我的代码如下:
class Animal(object):
__name = None #signifies lack of a value
__height = 0
__weight = 0
__sound = 0
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
class Dog(Animal):
def __init__(self, name, height, weight, sound, owner):
super(Dog, self).__init__(name, height, weight, sound)
self.__owner = owner
#self.__name = name this works if I uncomment this line.
__owner = ""
def toString(self):
return "{} belongs to {}".format(self.__name, self.__owner)
#return 'Sup dawg'
fido = Dog("Spot", 3, 4, "Woof", "John")
print(fido.toString())
最佳答案
以 __
为前缀的属性名称的目的是破坏它们,使子类无法轻松访问它们,以防止它们被意外覆盖。错误消息显示父类如何修改名称,因此您可以直接使用它:
def toString(self):
return "{} belongs to {}".format(self._Dog__name, self.__owner)
但您确实应该放弃前缀并使用常规名称。另外,不要定义 toString
方法;请使用 __str__ 来代替。类级初始化器也是不必要的。
class Animal(object):
def __init__(self, name, height, weight, sound):
self.name = name
self.height = height
self.weight = weight
self.sound = sound
class Dog(Animal):
def __init__(self, name, height, weight, sound, owner):
super(Dog, self).__init__(name, height, weight, sound)
self.owner = owner
def __str__(self):
return "{} belongs to {}".format(self.name, self.owner)
fido = Dog("Spot", 3, 4, "Woof", "John")
print(fido) # print will convert fido to a string implicitly, using its __str__ method
关于Python继承-对象没有属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871797/