模块(module)
模块(module) 的标准定义: if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module。也就是说,为了程序或者脚本的维护和使用的简便,把函数封装在文件中,然后在使用时操作他们实现功能。
模块的使用:
import time #标准库 安装python3就有的模块
import numpy #下载后可以得到的
import jessic #自定义模块,写在py文件中,和运行该模块在同级目录中
操作模块
import numpy as np #import 导入 np是简写
np.array([1,2,3]) #使用模块的功能,模块中有生成数组array的功能。逗号:运行该功能
import 的功能:1.首先执行调用的文件;2.再引入变量。模块封装的是功能函数。
不推荐用from xx import * 不同模块函数的变量名也许会重名。
模块路径:sys.path只认识执行函数的当前路径,不管这个执行文件引用的什么模块。总之,执行文件如果引用了自定义模块,或者执行文件引用的自定义模块还有引用其他自定义模块,如果这些自定义模块和执行文件不在一个目录,都要加上路径。
from my_file import func #my_file是import这个文件夹下的一个子文件夹路径,子文件夹中有func.py这个自定义模块。但是func和操作不在同级目录。
程序入口:bin.py 逻辑相关主文件: main.py
包package
用来组织模块。
举个栗子:
import matplotlib.pyplot as plt #pyplot是matplotlib的一个子库,可以通过这样的方式调用pyplot下的函数,比如
plt.figure() #但是不可以 a = matplotlib.pyplot.figure()
if __name__ = '__main__'
if name = __main__ print(__name__) 会输出 __main__ 如果在执行文件中就会执行,如果是被调用,那么__name__就不是main,不执行主函数。
作用:
1. 用于被调用文件的测试 放在调用文件最后,如果直接测试或者执行该调用函数,会执行if下面的代码。
2. 放于执行文件中,不想让执行文件变成调用文件。因为如果有人调用你的这个文件,但是想直接执行你的函数,因为name 不等于main,执行终止。防止其他人调用时调用模块的主函数。