星期三, 五月 09, 2007

python module __variable

sh$ cat module.py
#!/usr/bin/python

_var = 0
__var1 = 1
var2 = 2

def __func():
print "__func"
func = __func

sh$ cat main.py
#!/usr/bin/python

import module

v = module.__var1
print v
v = module._var
print v
f = module.__func
f()

class test:
def __init__(self):
self.v = module._var
# self.v = module.__var1 # (1)
# self.f = module.__func # (2)
self.v = module.var2
self.f = module.func # (3)
def run(self):
print self.v
self.f()

ti = test()
ti.run()
(1) 的输出:
sh$ python main.py
1
0
__func
Traceback (most recent call last):
File "main.py", line 23, in ?
ti = test()
File "main.py", line 15, in __init__
self.v = module.__var1
AttributeError: 'module' object has no attribute '_test__var1'
(2)的输出:
sh$ python main.py
1
0
__func
Traceback (most recent call last):
File "main.py", line 23, in ?
ti = test()
File "main.py", line 16, in __init__
self.f = module.__func
AttributeError: 'module' object has no attribute '_test__func'
在 module 层面都可以,但在 class 中 _var 可以但 __var 就不行,应该是和 class pseudo private 冲突了。当然 __var 是以 _ 开头,所以不能用 from module import __var 语法。

没有评论: