1
我正在试验基本的python继承与继承自Animal类的Dog类。由于某些原因,我的Dog对象不能正确继承name
,我一直收到AttributeError: 'Dog' object has no attribute '_Dog__name'
。有谁知道可能会发生什么?我的代码如下:Python的继承 - 对象没有属性错误
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())
**不要**使用双下划线名称混搭,除非你明白它的实际用途!它不是和“私人”访问修饰符一样的东西。另外,不要使用仅影响实例变量的类变量。 Python!= Java –
请不要使用本教程**。明确表示不是Python程序员的人,可能是写了很多Java代码的人。我的意思是认真的,'toString'? –