<p>如果您用两个下划线开始一个方法名,它将使它只能从该类访问。考虑以下示例:</p>
<pre><code>class A():
def __m(self):
pass
def m(self):
print(self.__m)
A().m() # <bound method A.__m of <__main__.A object at 0x10e0c1898>>
A().__m() # AttributeError: 'A' object has no attribute '__m'
</code></pre>
<p>那么<code>A().__m</code>怎么了?查看<code>A.__dict__</code>,在这里可以查找属性:</p>
<pre><code>>>> A.__dict__
mappingproxy({'__module__': '__main__', '_A__m': <function A.__m at 0x10e0ab730>, 'm': <function A.m at 0x10e0ab7b8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
</code></pre>
<p>最重要的是:</p>
<pre><code>'_A__m': <function A.__m at 0x10e0ab730>
</code></pre>
<p>因此,您编写的函数<code>__m</code>被重命名为<code>_A__m</code>。您不能从类之外的任何地方访问这些方法。你知道吗</p>
<p>如果类中有一个方法<code>show</code>调用一个方法<code>__method</code>(以<code>__</code>开头),它将只调用该类的该方法,因为它永远不知道<code>_B__method</code>,只知道<code>_A__method</code>。你知道吗</p>
<p>请注意,绝对不应该使用<code>_A__method</code>从类外部调用此方法。如果你需要做你正在做的事情,你应该用一个下划线。你知道吗</p>
<p>如果您真的需要<code>B</code>的<code>__method</code>方法是私有的,那么<code>B</code>也应该重写<code>show</code>:</p>
<pre><code>class A(object):
def __method(self):
print("hello")
def show(self):
self.__method()
class B(A):
def __method(self):
print("goodbye")
def show(self):
self.__method()
A().show() ## print out hello
B().show() ## print out goodbye
</code></pre>