[英]What does the `as` command do in 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
在某些情况下,它是用于对象命名的关键字。
from some_module import something as some_alias
# `some_alias` is `some_module.something`
with open("filename") as f:
# `f` is the file object `open("filename")` returned
try:
Nonsense!
except Exception as e:
# `e` is the Exception thrown
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.