【发布时间】:2013-10-05 11:42:57
【问题描述】:
我已经看过很多次了,但一直不明白as 命令在 Python 3.x 中的作用。能用简单的英文解释一下吗?
【问题讨论】:
-
这是一个保留关键字,至少在py2.6+中。
标签: python python-3.x command
我已经看过很多次了,但一直不明白as 命令在 Python 3.x 中的作用。能用简单的英文解释一下吗?
【问题讨论】:
标签: python python-3.x command
它是在某些情况下用于对象命名的关键字。
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
【讨论】:
它本身不是命令,它是用作with statement 一部分的关键字:
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
【讨论】:
with 声明的作用。你能解释一下吗?
with、try/except 和import 的文档