python中必备模块属性详解

在python中,每个模块(或脚本)都是可以独立运行的,为了区分不同的模块,每个模块都有对应的系统变量,这些系统变量都以前后加双下划线的形式命令,如__doc____file____name__等。本文将列出几个常用的模块属性。

__name__

__name__是用于标识模块名字的系统变量。

首先将主程序定义为被直接运行的模块,在主程序中变量__name__的值是__main__,在被导入的模块中,变量__name__的值是被导入模块的名字(不含.py后缀),如file1

__name__可以告诉解释器模块是作为程序直接运行还是被导入其他程序中使用,如果模块中有一部分代码,我们希望只在模块作为主程序运行时才被执行,那么__name__将非常有用。

举例来说,模块file1.py内容如下:

1
2
3
4
5
6
# file1.py
def function():
pass
print('file1 is called!')
if __name__ == '__main__':
print('file1 is the main program!')

模块file2.py内容为:

1
2
3
# file2.py
import file1
print('file2 is called!')

那么只有在直接运行file1.py时才会输出file1 is the main program!

1
2
3
4
5
6
$ python file2.py
file1 is called!
file2 is called!
$ python file1.py
file1 is called!
file1 is the main program!

__name__常用于在模块中增加测试代码。

__file__

__file__属性记录模块的绝对路径,这在需要获取模块路径的时候非常常用:

1
2
3
>>> import file1
>>> file1.__file__
/home/ven/file1.py

__all__

__all__定义了模块的公有接口,决定了当使用from <module> import *时哪些内容会被导入。需要注意的是__all__对于from <module> import <member>并没有影响。

依然是以file.py为例,内容为:

1
2
3
4
5
6
# file1.py
a = 1
b = 2
def func():
pass
__all__ = ['a', 'func']

那么在使用from file1 import *时变量b将不会被导入:

1
2
3
4
5
6
7
8
>>> from file1 import *
>>> a
1
>>> b
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
b
NameError: name 'b' is not defined

但是如果我们使用其他方法导入file1.pyb的导入将不受影响:

1
2
3
4
>>> import file1  # fine
>>> file1.b
2
>>> from file1 import b # fine

然而,我们通常不鼓励使用import * 的形式,而一旦使用这种导入形式,那么为了防止因全部导入导致程序混乱,使用__all__管理公有接口是很有必要的。