我正在尝试使用继承自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())
答案 0 :(得分:4)
__
- 前缀属性名称的目的是破坏它们,以便子类无法轻松访问它们,以防止它们被意外覆盖。该错误消息显示父类如何破坏名称,因此您可以直接使用它:
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