as命令在Python 3.x中有什么作用?
问题内容:
我已经看过很多次了,但从未理解该as
命令在Python 3.x中的作用。能用简单的英语解释吗?
问题答案:
它本身不是命令,它是with
语句中使用的关键字:
with open("myfile.txt") as f:
text = f.read()
之后,为对象 as
分配由with
上下文管理器处理的表达式的结果。
另一个用途是重命名导入的模块:
import numpy as np
因此您可以使用名称np
代替numpy
现在。
第三种用途是使您可以访问Exception
对象:
try:
f = open("foo")
except IOError as exc:
# Now you can access the Exception for more detailed analysis