简单讲:
【 import Test_1 】只是导入了 Test_1.py 这个模块 ,并没有导入模块内的函数,要使用这个模块内的函数 (例如 hello 函数 ),只能用 Test_1.hello(###) 的方法;
【 from Test_1 import hello 】从 Test_1 模块导入 hello 函数 ,要使用这个函数,只需要 hello(###) 就行了, 不需要 Test_1.hello(###)。
Python中,import 语句是用于引入模块的。Python 的模块是一个 Python 文件,以 .py 结尾。模块能定义函数,类和变量。
首先定义一个简单模块 Test_1.py
#------------- Test_1.py 模块-----------------------------------------
def hello():
print('hello world')
return
def bye():
print('bye!')
return
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import XXX如下图,使用 import 语句导入模块:
#------------- 在其他文件中调用 hello 函数---------------------------- #!/usr/bin/python # -*- coding: UTF-8 -*- # 导入模块 import Test_1 ------------------------------------------------------------ # 使用 Test_1.hello() 调用 hello 函数,*成功* Test_1.hello() >>> hello world ------------------------------------------------------------ # 直接使用 hello() 调用 hello 函数,*报错* hello() >>> Traceback (most recent call last): File "D:/1/example/main.py", line 9, inTest() NameError: name 'hello' is not defined ------------------------------------------------------------
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
from XXX import XXX如下图,使用 from 【模块】 import 【函数】导入模块内的函数:
#------------- 在其他文件中调用函数---------------------------- #!/usr/bin/python # -*- coding: UTF-8 -*- # 导入模块内的 hello 函数,但没有导入 bye 函数 from Test_1 import hello ------------------------------------------------------------ # 调用 hello 函数,* 成功 * hello() >>> hello world ------------------------------------------------------------ # 调用 bye 函数,* 报错 * bye() >>> Traceback (most recent call last): File "D:/1/example/main.py", line 15, inTest() NameError: name 'bye' is not defined ------------------------------------------------------------
上图仅从 Test_1.py 模块导入了 hello 函数,当前命名空间没有导入 bye,因此调用 bye 函数失败
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
from 【模块】 import * ,将指定模块内的所有内容导入到当前命名空间
#------------- 在其他文件中调用函数---------------------------- #!/usr/bin/python # -*- coding: UTF-8 -*- # 导入模块内的所有函数至当前命名空间 from Test_1 import * ------------------------------------------------------------ # 调用 hello 函数,* 成功 * hello() >>> hello world ------------------------------------------------------------ # 调用 bye 函数,* 成功 * bye() >>> bye! ------------------------------------------------------------
以上,Bye!



