python - 从子类访问python父类变量

标签 python

为什么这行不通?

class Parent:
    __var = "Whatever"

class Child(Parent):
    def printVar(self):
        print(self.__var)


Timmy = Child()

Timmy.printVar()

我得到以下异常:

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<stdin>", line 3, in printVar
AttributeError: 'Child' object has no attribute '_Child__var'

最佳答案

这是因为您选择使用双前导下划线命名属性。这会触发一些名称修改

您可以通过 self._Parent__var 访问它

In [8]: class Parent:
    __var = "Whatever"
   ...:     
In [9]: class Child(Parent):
    def foo(self): print self._Parent__var
   ...:     
In [10]: a=Child()
In [11]: a.foo()
Whatever

更多信息可在 python 文档中找到,网址为 https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references

关于python - 从子类访问python父类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38357253/

相关文章:

python - 如何使用python解析ld+json

python - 在GAE控制面板中设置环境变量

python - Xpath - 无法使用 Text() 获取信息,但我看不到路径和数字

python - 计算两个列表的所有 IoU 的有效方法

python - MXNet 打印中间符号值

Python - Selenium : Find/Click YT-Like Button

Python requests 模块 - 将嵌套 XML 作为查询参数传递

python - 使用Python更新mysql错误

python - 奇怪的 eclipse-pydev 控制台行为

python - MySQLdb执行超时