python--特殊变量

1. __all__

Paste_Image.png

from module import *, 默认导出不以下划线开头的所有成员, 但是加了__all__, 导出列表中的所有。

In [1]: from hello import *

In [2]: _name
Out[2]: 'xiaoming'

In [3]: test_hello()
hello

In [4]: age
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-cfd449bec15d> in <module>()
----> 1 age

NameError: name 'age' is not defined

In [5]: _test_name()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-3b45bfdd4d41> in <module>()
----> 1 _test_name()

NameError: name '_test_name' is not defined

注意
__all__ 只影响到了 from module import * 这种导入方式,对于 from module import member 或者 import module 导入方式并没有影响,仍然可以从外部导入.

In [6]: from hello import age

In [7]: age
Out[7]: 18

In [8]: import hello

In [9]: hello.age
Out[9]: 18
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容