<p>通过<code>.__</code>访问的属性在类主体</em>的任何地方都会被损坏(但是内部类声明会首先到达它)。你知道吗</p>
<p>把它想象成句法上的糖。</em></p>
<p>在<code>Test</code>类主体的上下文中,<code>self.__test</code>是损坏名称<code>self._Test__test</code>的<em>别名</em>;在上下文中,它们的意思完全相同。你知道吗</p>
<p>一个示范会让这更清楚。首先,一些助手类。你知道吗</p>
<pre><code>class PrintAttrAccess:
def __getattr__(self, name):
print(name)
class Empty: pass
</code></pre>
<p>现在演示一下:</p>
<pre><code>class Test:
print('IN TEST BODY')
(lambda: PrintAttrAccess().__in_lambda)() # Anywhere in the class body works.
classfoo = Empty()
classfoo.__foo = 'foo'
print("Same thing?", classfoo.__foo is classfoo._Test__foo)
print("vars() of classfoo:", vars(classfoo))
class Inner:
print('IN INNER')
PrintAccess().__inner
def __init__(self):
print('IN INIT')
print("Who am I?", self)
self.__test = "cats"
print(self._Test__test) # It's ALREADY MANGLED!
# This line means exactly the same as the one above.
print(self.__test)
localfoo = Empty()
localfoo.__spam = 'spam' # "self" isn't special.
print("vars() of localfoo:", vars(localfoo))
def outside_method(self):
print('OUTSIDE BODY')
print("Who am I?", self)
self.__test = "dogs"
print(self._Test__test)
print(self.__test) # Sugar doesn't apply outside of class body.
Test.outside_method = outside_method # Add a new method to Test class.
Test().outside_method() # init and call as method.
</code></pre>
<p>输出为:</p>
<pre><code>IN TEST BODY
_Test__in_lambda
Same thing? True
vars() of classfoo: {'_Test__foo': 'foo'}
IN INNER
_Inner__inner
IN INIT
Who am I? <__main__.Test object at 0x000001CCF3048978>
cats
cats
vars() of localfoo: {'_Test__spam': 'spam'}
OUTSIDE BODY
Who am I? <__main__.Test object at 0x000001CCF3048978>
cats
dogs
</code></pre>