之前总疑惑,在网上下载的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文件,删掉没关系,必要的时候系统会再生成。