【问题标题】:What does the `as` command do in Python 3.x?Python 3.x 中的 as 命令有什么作用?
【发布时间】:2013-10-05 11:42:57
【问题描述】:

我已经看过很多次了,但一直不明白as 命令在 Python 3.x 中的作用。能用简单的英文解释一下吗?

【问题讨论】:

  • 这是一个保留关键字,至少在py2.6+中。

标签: python python-3.x command


【解决方案1】:

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

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

【讨论】:

  • 第二种和第三种情况真的不是重命名吧?
  • @TimPietzcker:是的,我认为这只是命名。
  • 那么在“重命名”之前的名字是什么?
  • @TimPietzcker 你是唯一提到重新命名的人。 Kabie 刚刚说这是关于命名。
【解决方案2】:

它本身不是命令,它是用作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 声明的作用。你能解释一下吗?
  • 我在 Python 官方文档中找不到任何关于“as”语句的技术参考。有人知道吗?
  • @BrianHVB:由于它不是“独立”关键字,您需要查看withtry/exceptimport 的文档
猜你喜欢
  • 2012-08-07
  • 2016-04-14
  • 2017-10-13
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 2013-10-02
  • 2023-03-23
相关资源
最近更新 更多