为什么这行不通?
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/