之前总疑惑,在网上下载的python代码包总有好多程序,其实不光可以导入常见的模块像numpy,math,time等,任何python程序都可以作为模块导入。
一.超简单版
1.新建工程pycharmproject
2.新建py文件hello.py
print("hello,word")
3.新建py文件importhello.py
import hello
4.运行importhello.py,结果:
hello,word
二.包含函数的简单模块
1.新建hello.py
def hello():
print("hello,word")
2.新建importhello.py
import hello
hello.hello()
3.运行importhello.py,结果:
hello,word
三.模块中包含测试代码
1.新建hello.py
def hello():
print("hello,word")
hello()
2.新建importhello.py
import hello
hello.hello()
3.运行importhello.py,结果:
hello,word
hello,word
出现两次hello,word,这是因为在import hello模块的过程中(由于hello程序有运行hello()),所以import时出现一次hello,word,再运行hello.hello时,又会运行一次,怎样避免这种情况,看四。
四.使用_name_变量(当程序作为程序运行时,函数会被执行;当程序作为模块导入时,就变得像普通模块一样)
1.新建hello.py
def hello():
print("hello,word")
def test():
hello()
if __name__=='_main_':test()
2.新建importhello.py
import hello
hello.hello()
3.运行importhello.py,结果:
hello,word
注意:name两边的下划线是2+2=4条,否则会出现错误:NameError: name '_name_' is not defined。
在导入模块的时候,会自动建立文件夹并生产pyc文件:
这是系统自动生成的能够更有效处理的文件,之后再导入同样的模块时,会导入pyc文件,删掉没关系,必要的时候系统会再生成。
from 模块 import 工具
使用from...import时,表示从模块中导入部分工具,导入后可以直接使用此工具,不需要用模块名.工具
注意:如果两个模块,存在同名的函数,后导入的会覆盖先导入的,因此,import都写在文件顶部,若想避免冲突,可以用as起一个别名
from 模块 import *
把模块中所有工具都导入,可以直接使用工具,但是开发中不推荐使用,不容易排查多个模块中存在同名函数的情况
使用模块名.__file__可以查看模块的完整路径,注意不要和系统的模块文件重名
五. 包(将模块组合起来)
包是一个文件夹,文件夹中包含各种py模块,目录必须包含文件__init__.py
使用python package可以直接创建一个带__init__.py的包
要在外界使用包中的模块,需要在__init__.py中指定对外界提供的模块列表