当尝试从类访问 __variables
时,解析器假定2个下划线相对于当前类是私有的 . 注意一个不相关的函数如何获得"private"变量 .
这是一个错误吗?
>>> def f(): pass
...
>>> class A:
... def g(self):
... f.__x = 1
... def h():
... pass
... h.__y = 2
... return h
...
>>> z = A().g()
>>> dir(z)
['_A__y', '__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get_
_', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new
__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_
closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals',
'func_name']
>>> dir(f)
['_A__x', '__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get_
_', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new
__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_
closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals',
'func_name']
在python 2.5和3.2上测试过
1 回答
这是well documented behavior .