Java 企业应用
不要温柔的走入那个良夜

在python的module中,可以使用 __all__ 函数来定义这个module像其他引用自己的module导入的变量:

例如:

alltag.py

__all__ = ['bar', 'baz']
 
waz = 5
bar = 10
def baz(): return 'baz'

 

alltagtest.py

from alltag import * 
 
print bar
print baz 
 
# The following will trigger an exception, as "waz" is not exported by the module
print waz
 

 

运行alltagtest.py结果:

image

虽然使用了import * 声明,但是waz并没有被导入,这是因为__all__函数发挥了作用。

而如果将__all__注释掉,那么就是对alltag的命名空间进行了全部的import,所以,__all__可以隐藏不想被import的默认值。

==============================================================================

refer:

it's a list of public objects of that module -- it overrides the default of hiding everything that begins with an underscore

If the __all__ above is commented out, this code will then execute to completion, as the default behaviour of import * is to import all symbols that do not begin with an underscore, from the given namespace.

Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.

FROM:http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python

posted on 2012-07-24 08:48 cpegtop 阅读(2911) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: