模块

模块

导入模块

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值