2017-08-24 670 views
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()) 
+0

**不要**使用双下划线名称混搭,除非你明白它的实际用途!它不是和“私人”访问修饰符一样的东西。另外,不要使用仅影响实例变量的类变量。 Python!= Java –

+0

请不要使用本教程**。明确表示不是Python程序员的人,可能是写了很多Java代码的人。我的意思是认真的,'toString'? –

回答

4

__ -prefixed属性名的目的是损坏它们,这样子类无法方便地访问它们,以防止它们被意外覆盖。该错误消息显示你的父类如何轧液的名字,所以你可以直接使用:

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 
相关问题