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

有些话、适合烂在心里 提交于 2019-12-01 01:11:11

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

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

It is a keyword used for object naming in several cases.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!