Python private class variables that aren't class variables
当试图从类访问
这是虫子吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | >>> 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上测试
这是一个记录良好的行为。
This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.