繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM