class Test():
def __init__(self):
self.__test = "cats"
print(self.__test)
def __example(self):
print("Hello World")
x = Test()
print(x.__dict__)
使用我上面写的代码,打印语句将显示访问变量test
,我需要写_Test__test
,但是如图所示我可以打印变量如果我之后直接在 __init__
方法中调用它。所以我的问题是,如果我可以在用它的名称声明后直接访问它,即 self.__test
,那么它会在什么时候变得困惑?
最佳答案
通过 .__
访问的属性在类体中任何地方都被破坏了(但是内部类声明会首先到达它。)。
将其视为语法糖。
在 Test
的上下文中类(class)机构,self.__test
是被破坏的名称 self._Test__test
的别名 ;在上下文中,它们的意思完全相同。
演示会使这一点更清楚。首先,一些辅助类。
class PrintAttrAccess:
def __getattr__(self, name):
print(name)
class Empty: pass
现在进行演示:
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.
输出是:
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
关于python - 使用双下划线时什么时候会发生名称重整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53568069/