`as'命令在Python 3.x中做什么? [英] What does the `as` command do in Python 3.x?

查看:184
本文介绍了`as'命令在Python 3.x中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过很多次,但从来没有理解作为命令在Python 3.x中的作用。你能用简单的英语解释一下吗?

I've seen it many times but never understood what the as command does in Python 3.x. Can you explain it in plain English?

推荐答案

这不是一个命令本身, href =http://docs.python.org/2/reference/compound_stmts.html#the-with-statement> with 语句:

It's not a command per se, it's a keyword used as part of the with statement:

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

作为后的对象被赋予表达式的结果与上下文管理器。

The object after as gets assigned the result of the expression handled by the with context manager.

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

Another use is to rename an imported module:

import numpy as np

您现在可以使用 np 而不是 numpy

so you can use the name np instead of numpy from now on.

第三种用法是让您访问异常对象:

The third use is to give you access to an Exception object:

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

这篇关于`as'命令在Python 3.x中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆