在python中继承时,我得到了私有变量跟随错误:
AttributeError:'dog'对象没有属性'_dog__name'
我搜索了很多,但不明白我的问题在哪里;
class animal(object):
__name = ""
__height = ""
__weight = ""
__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 and {} weight 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 and {} weight and say {} and belongs to {}.".format(self.__name, self.__height,
self.__weight, self.__sound,
self.__owner)
puppy = dog('puppy', 45, 15, 'bark', 'alex')
puppy.toString()
答案 0 :(得分:2)
当您使用双下划线创建var时,它只是用于将其指示为私有变量的符号,python会对变量名本身进行名称修改,以防止以正常方式访问它。
然而,它仍然不是真正的私有变量,如C / C ++。你仍然可以访问所谓的python“private var”,其语法如下
var = __myvar
# access with _<class name>__myvar
来自PEP,
对于你的情况,将你的dog class toString方法更改为下面然后它应该可以
def toString(self):
return "{} is {} cm and {} weight and say {} and belongs to {}.".format(self._animal__name, self._animal__height,
self._animal__weight, self._animal__sound,
self.__owner) # __owner remains because its not inherit from class animal
另一种选择是将动物类变量更改为单个下划线_
,如果你真的不需要双下划线__