What does the `as` command do in Python 3.x?
我见过很多次,但从来没有理解过python 3.x中的
它本身不是命令,而是用作
1 2 | with open("myfile.txt") as f: text = f.read() |
另一个用途是重命名导入的模块:
1 | import numpy as np |
号
所以从现在起你可以用
第三种用途是让您访问
1 2 3 4 | try: f = open("foo") except IOError as exc: # Now you can access the Exception for more detailed analysis |
在某些情况下,它是用于对象命名的关键字。
1 2 3 4 5 6 7 8 9 10 | 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 |
。