【问题标题】:inheriting private variable in python [duplicate]在python中继承私有变量[重复]
【发布时间】:2017-04-08 04:26:23
【问题描述】:

在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()

【问题讨论】:

  • 不,这是关于变量,而不是方法。
  • 机制是一样的。哎呀,它甚至会影响类语句中的局部变量和导入的模块。

标签: python inheritance


【解决方案1】:

当您创建带有双下划线的 var 时,它只是一种用于将其表示为私有变量的符号,python 会对变量名本身进行名称修改以防止正常方式访问它。

但是,它仍然不是像 C/C++ 那样真正的私有变量。您仍然可以使用以下语法访问所谓的 python“private var”

var = __myvar
# access with _<class name>__myvar

来自PEP

  • _single_leading_underscore:弱“内部使用”指标。例如。 from M import * 不导入名称以 下划线。
  • __double_leading_underscore : 命名类属性时,调用名称修改(在类 FooBar 中,__boo 变为 _FooBar__boo

对于您的情况,将您的狗类 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

如果您真的不需要双下划线__,另一种选择是将您的动物类变量更改为单下划线_

【讨论】:

  • tnx,python 3 和 2 一样吗?
  • 我想是的,python 2和3应该是一样的
  • 因为在这个视频中,教练运行完全相同的代码没有任何错误; youtu.be/N4mEzFDjqtA?t=39m44s
  • 我已经用我的 python3.2 进行了测试,它与 python2 的行为相同,python 3 文档https://docs.python.org/3/tutorial/classes.html 显示名称修改相同,不知道为什么它在视频中有效
猜你喜欢
  • 2017-09-07
  • 2014-11-17
  • 2017-12-01
  • 2014-04-06
  • 2018-09-19
  • 1970-01-01
  • 2011-04-06
  • 2015-09-14
  • 1970-01-01
相关资源
最近更新 更多