Python 3.2“with/as”是什么意思?做
我正在学习 Python,并且正在尝试 with **** as ****:
语句。我认为它的工作原理很像 C# 的 using(****) {
,但我担心我正在遵循过时的示例。
这是我的代码:
# -*- coding: iso-8859-1 -*-
import pprint
pow = 1, 2, 3
with pprint.pprint as pprint:
pprint(pow)
我假设这里发生的事情是我的小闭包中的 pprint
是 pprint.pprint
函数的别名。不过,我遇到了一个奇怪的错误:
Traceback (most recent call last):
File "test.py", line 7, in <module>
with pprint.pprint as pprint:
AttributeError: __exit__
所以现在我想我正在使用旧版本 Python 的语法,就像我之前所做的那样 (print "Hello"
)
为什么我的代码不工作正如预期的那样?
I'm learning Python, and I'm trying out the with **** as ****:
statement. I figure it works much like C#'s using(****) {
, but I'm afraid I'm following outdated examples.
This is my code:
# -*- coding: iso-8859-1 -*-
import pprint
pow = 1, 2, 3
with pprint.pprint as pprint:
pprint(pow)
I assume what's happening here is pprint
in my small closure is an alias for the pprint.pprint
function. I'm getting a weird error though:
Traceback (most recent call last):
File "test.py", line 7, in <module>
with pprint.pprint as pprint:
AttributeError: __exit__
So now I'm thinking I'm using syntax from an older version of Python like I did earlier (print "Hello"
)
Why isn't my code working as expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
with
不是这样工作的。它被设计为自动清理块末尾的对象,例如,而不是
You can do
并且关闭会自动发生。
有关详细信息,请参阅PEP 343 --“with”声明和Python 2.5 的新增功能 - PEP 343有关如何使用它的更多示例。
with
doesn't work like that.It's designed to automatically clean up an object at the end of a block, e.g. instead of
You can do
and the close happens automatically.
See PEP 343 -- The "with" Statement for details and What's New in Python 2.5 - PEP 343 for some more examples of how you can use it.
with
语句并不旨在执行您期望的操作。它使用“上下文管理器协议”,因此,期望传递一个 上下文管理器。要创建别名,只需将其分配给一个新变量:
The
with
statement isn't intended to do what you expect. It uses the "context manager protocol", and as such, expects to be passed a context manager.To create an alias, just assign it to a new variable:
您使用它期望它为现有名称添加别名,但 在 Python 中
期望传递一个上下文管理器。
pprint.pprint
不是上下文管理器。You're using it expecting it to alias an existing name, but in Python
with
expects to be passed a context manager.pprint.pprint
is not a context manager.别名不是
with
的用途。您可能想要的是这样的:Aliasing is not what
with
is for. What you probably want is this: