python __all__ 含义

2018-07-02  本文已影响0人  tafanfly

1. 背景

最近看了一些代码,发现有些python文件在import 下面声明 __all__,查阅资料了解其含义。

2. 含义

3. 用例

被测文件test.py

__all__ = ['a',
           'b',
           'run',]

a = 'aaa'
b = 'bbb'
c = 'ccc'

def run():
    print 'Run the function.'

测试结果

test 1:

In [1]: from test import *

In [2]: print a
aaa

In [3]: print b
bbb

In [4]: run
Out[4]: <function test.run>

In [5]: run()
Run the function.

In [6]: print c
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-1b1d2b33e8c2> in <module>()
----> 1 print c

NameError: name 'c' is not defined

test 2:

In [7]: from test import c

In [8]: print c
ccc

注意

上一篇 下一篇

猜你喜欢

热点阅读