`as`命令在Python 3.x中有什么作用?

What does the `as` command do in Python 3.x?

我见过很多次,但从来没有理解过python 3.x中的as命令。你能用简单的英语解释一下吗?


它本身不是命令,而是用作with语句的一部分的关键字:

1
2
with open("myfile.txt") as f:
    text = f.read()

as之后的对象被分配由with上下文管理器处理的表达式的结果。

另一个用途是重命名导入的模块:

1
import numpy as np

所以从现在起你可以用np代替numpy

第三种用途是让您访问Exception对象:

1
2
3
4
try:
    f = open("foo")
except IOError as exc:
    # Now you can access the Exception for more detailed analysis


在某些情况下,它是用于对象命名的关键字。

1
2
3
4
5
6
7
8
9
10
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