我曾多次见到它,但从未理解Python 3.x中
as
命令的作用。你能用简单易懂的英语解释一下吗?as
命令的作用。你能用简单易懂的英语解释一下吗?这并不是一个命令,而是作为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
with
语句是做什么的。你能解释一下吗? - user2820691with
、try/except
和import
的文档。 - Tim Pietzcker在多种情况下,它是用于对象命名的关键字。
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