Python - 从子类方法访问父属性很奇怪

时间:2017-07-11 19:11:18

标签: python class inheritance parent

import random
import sys
import os
class Animal:
    __name = ""
    __height = 0
    __weight = 0
    __sound = ""

    def __init__(self, name, height, weight, sound):
        self.__name = name
        self.__height = height
        self.__weight = weight
        self.__sound = sound

    def toString(self):
        return "{} is {} cm tall and {} kilograms and say {}".format(self.__name,
                                                                     self.__height,
                                                                     self.__weight,
                                                                     self.__sound)

class Dog(Animal):
    __owner = ""
    def __init__(self, name, height, weight, sound, owner):
        self.__owner = owner
        super(Dog, self).__init__(name, height, weight, sound)

    def toString(self):
        return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
                                                                                      self.__height,
                                                                                      self.__weight,
                                                                                      self.__sound,
                                                                                      self.__owner)

spot = Dog("Spot", 53, 27, "Ruff", "Derek")
print(spot.toString())

运行时,此代码打印:

    return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
AttributeError: 'Dog' object has no attribute '_Dog__name'

但是当我把Dog类中的toString方法放到一边时,就像这样:

class Dog(Animal):
    __owner = ""
    def __init__(self, name, height, weight, sound, owner):
        self.__owner = owner
        super(Dog, self).__init__(name, height, weight, sound)

        def toString(self):
            return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
                                                                                      self.__height,
                                                                                      self.__weight,
                                                                                      self.__sound,
                                                                                      self.__owner)

打印得很好,说:

斑点高53厘米,重27公斤,并说Ruff

为什么会这样?

编辑:我刚刚意识到打印的东西是Animal的toString方法,而不是Dog的toString方法。

2 个答案:

答案 0 :(得分:3)

不要将属性分类为默认值或“声明”,也不要使用launchScript(test) - 前缀名称,除非您了解为什么您可能需要使用此类名称。此外,您不需要__; toString具有相同的用途,可根据需要自动调用。

__str__

答案 1 :(得分:2)

私有属性只是......私有。 Python中没有受保护变量的概念。通过使用双下划线限制变量,甚至可以防止子类访问它们。