Python继承-对象没有属性错误

标签 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())

最佳答案

__ 为前缀的属性名称的目的是破坏它们,使子类无法轻松访问它们,以防止它们被意外覆盖。错误消息显示父类如何修改名称,因此您可以直接使用它:

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/

相关文章:

css - css 只继承一个属性

python - sympy 简化虚数的分数幂

perl - 在 Moose 中,如何判断一个对象的类是否是另一个对象类的子类?

python - 作业,Python 3 : Changing a Variable Type From Within a Function

python - catboost 分类器可以解决类别不平衡问题吗?

c++ - 简单的一行类方法返回错误值

java - 需要帮助编译此迭代和接口(interface)程序

ios - IBOutlet 连接和继承

python 2.4日志记录-循环内的动态日志文件名

Python - 对元组列表进行排序