模块
导入模块
import 模块名(不需要 .py 后缀)导入模块,相当于我们在 main.py 里借用并运行了 other.py 文件里的代码,因此运行结果是 带你打开编程世界的大门。你可以理解为 Python 会将 import other 语句替换成 other.py 里的代码。
# other.py
print('带你打开编程世界的大门')
# main.py
print('hi')
import other
print('bye')
# 输出结果:
# hi
# 带你打开编程世界的大门
# bye
import 语句还有一种用法是 import … as …,比如我们觉得 other 这个模块名太长,就可以用 import other as o,相当于给 other 取了一个别名为 o,之后我们就可以使用 o 来替代 other。
# other.py
pi = 3.14159265359
def half(x):
return x / 2
# main.py
import other as o # 导入 other 模块
print(o.pi)
# 输出:3.14159265359
print(o.half(4))
# 输出:2.0
import 语句一次性将整个模块导入进来,我们还可以使用 from … import … 语句只导入我们需要的变量、函数等。举个例子:
# other.py
pi = 3.14159265359
def half(x):
return x / 2
# main.py
from other import pi, half # 从 other 模块导入 pi 和 half
print(pi)
# 输出:3.14159265359
print(half(4))
# 输出:2.0
可以看到,执行 from other import pi, half 后可以直接使用 other.py 里的 pi 和 half,不再需要在前面加 other.。并且同时导入多个变量或函数时,两两之间要用逗号隔开。
需要注意的是:使用 from … import … 的方式导入就不能再用 模块名.变量名 和 模块名.函数名 的方式访问模块内的变量或函数了,否则代码将会报错:
# other.py
pi = 3.14159265359
def half(x):
return x / 2
# main.py
from other import pi, half
print(pi)
# 输出:3.14159265359
print(other.half(4))
# 报错:NameError: name 'other' is not defined on line 6