python关于__all__的定义

原文: http://hi.baidu.com/_yuan0518/item/f21bee4ead5c5aef1f19bc21


__all__

See import.

The public names defined by a module are determined by checking themodule's namespace for a variable named __all__; if defined, itmust be a sequence of strings which are names defined or imported bythat module. The names given in __all__ are all consideredpublic and are required to exist. If __all__ is not defined, theset of public names includes all names found in the module's namespacewhich do not begin with an underscore character ("_"). __all__should contain the entire public API. It is intended to avoidaccidentally exporting items that are not part of the API (such aslibrary modules which were imported and used within the module).

 

Python的moudle是很重要的一个概念,我看到好多人写的moudle里都有一个__init__.py文件。有的__init__.py中是空白,有的却会有__all__参数。搜索了下总结下__all__参数的作用。

如果其他页面import *的时候如果__init__.py是空白的,可以直接import到moudle的所有函数。而如果__init__.py中定义了__all__,则import *的时候只会导入__all__部分定义的内容。


例如,我们可以这样组织一个package:

package1/
__init__.py
subPack1/
__init__.py
module_11.py
module_12.py
module_13.py
subPack2/
__init__.py
module_21.py
module_22.py
……
__init__.py可以为空,只要它存在,就表明此目录应被作为一个package处理。当然,__init__.py中也可以设置相应的内容,下文详细介绍。

好了,现在我们在module_11.py中定义一个函数:

def funA():
print "funcA in module_11"
return

在顶层目录(也就是package1所在的目录,当然也参考上面的介绍,将package1放在解释器能够搜索到的地方)运行python:

>>>from package1.subPack1.module_11 import funcA
>>>funcA()
funcA in module_11

这样,我们就按照package的层次关系,正确调用了module_11中的函数。

细心的用户会发现,有时在import语句中会出现通配符*,导入某个module中的所有元素,这是怎么实现的呢?
答案就在__init__.py中。我们在subPack1的__init__.py文件中写

__all__ = ['module_13', 'module_12']

然后进入python

>>>from package1.subPack1 import *
>>>module_11.funcA()
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named module_11

也就是说,以*导入时,package内的module是受__init__.py限制的。

好了,最后来看看,如何在package内部互相调用。
如果希望调用同一个package中的module,则直接import即可。也就是说,在module_12.py中,可以直接使用

import module_11

如果不在同一个package中,例如我们希望在module_21.py中调用module_11.py中的FuncA,则应该这样:

from module_11包名.module_11 import funcA


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值