Python – __all__ function

在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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值