Tru*_*ran 2 python inheritance
我正在尝试使用继承自 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())
Run Code Online (Sandbox Code Playgroud)
带 - 前缀的属性名称的目的__是破坏它们,使子类无法轻松访问它们,以防止它们被意外覆盖。错误消息显示父类如何修改名称,因此您可以直接使用它:
def toString(self):
return "{} belongs to {}".format(self._Dog__name, self.__owner)
Run Code Online (Sandbox Code Playgroud)
但您确实应该放弃前缀并使用常规名称。另外,不要定义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
Run Code Online (Sandbox Code Playgroud)