【发布时间】:2017-07-24 19:53:54
【问题描述】:
class A(object):
def __get(self):
pass
def _m(self):
return self.__get()
class B(A):
def _m(self):
return str(self.__get())
print(A()._m())
print(B()._m())
为什么print(A()._m()) 打印None,但print(B()._m()) 引发AttributeError: 'B' object has no attribute '_B__get'?
我认为双下划线可以防止方法覆盖。
更新
您写道__get 是私有的。
那么为什么以下工作?
class A(object):
def __get(self):
pass
def _m(self):
return self.__get()
class B(A):
pass
print(A()._m())
print(B()._m())
为什么这段代码没有引发AttributeError 并打印None 两次?
【问题讨论】:
-
Name mangling。您在
B中对self.__get()的调用实际上是在调用self._B__get(),它不存在。除非您想要这种行为,否则不要使用前导双下划线。 -
查看what is the meaning of a single and a double underscore before an object name和一些链接的问题,因为有一些详细的解释。
-
重新更新:因为您正在从类 A 中定义的方法调用 __get。这在任何支持私有概念的语言中都是完全合法的——事实上,这是私有的最常见用例方法。
标签: python