Python模块的深入
Python模块信息
当我们创建一个空的py文件时,就已经定义了一个Python模块,里面带有一些信息,这些信息可以用dir()函数查看。
比如创建一个空的py模块,文件名为t05.py,代码如下。
print(dir())
程序运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t05.py
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
Process finished with exit code 0
引入其他模块后
import sys
from mytools import myadd
import mytools.myappend
print(dir())
程序运行结果如下,列表中包括引入的模块或包'myadd', 'mytools', 'sys'。
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t05.py
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'myadd', 'mytools', 'sys']
Process finished with exit code 0
我们可以输出比较常用的___file和_name__信息。
print(__file__)
print(__name__)
程序运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t05.py
E:/wkp01/p00/test01/atestpkg/t05.py
__main__
Process finished with exit code 0
模块的测试运行与__main__判断
模块的__main__属性可以判断此模块处于主运行还是被import引入。
如果希望模块中的一些代码作为主程序时才运行,而作为import时不要运行,那么__main__判断很有用。
比如在myappend.py模块中
alist=[1,2,3]
def funapd(n):
return alist*n
# 上面的代码在import时执行
if __name__=="__main__":
# 下面以后的代码在import引入时不会运行,只在单独运行此模块时才会执行
print("alist的长度是:",len(alist)) # 3