Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
172
11
def pick():
import random
return random.choice(places)
与编程的许多方面一样,使用你觉得最清晰的形式。模块限定的名称(
random.choice
)更
安全,但需要多敲几次键盘。
如果导入的代码可能会用在不止一处,可以考虑从函数外部导入;如果知道其使用范围
有限,就在函数内部导入。有些人为了使代码之间的依赖关系清晰可见,喜欢把所有的
import
全放在文件开头部分。这两种方法都可行。
11.1.2
使用别名导入模块
在主程序
lunch.py
中,我们使用了
import fast
。但是出现以下情况该怎么办?
还有另一个名为
fast
的模块。
希望使用更好记的名称。
想尽量少敲几个字。
为此,可以使用
别名
来导入模块,如例
1
1-4
所示。这里使用别名
f
11-4
fast3.py
import fast as f
place = f.pick()
print("Let's go to", place)
11.1.3
导入部分模块
可以导入整个模块,也可以仅导入其中的一部分。你刚刚看到了后者:我们只需要
random
模块中的
choice()
函数。
和模块一样,也可以为导入的部分内容使用别名。
首先使用原始名称从
fast
模块中导入
pick()
,如例
11-5
所示。
11-5
fast4.py
from fast import pick
place = pick()
print("Let's go to", place)
然后使用
who_cares ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223