0

我正在阅读PEP 343并尝试举一些例子。但我现在还不是很清楚。特别是因为我有一个错误:

>>> def f():
...     return 'f'
... 
>>> with f(): # or as f
...     print f() # or f
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __exit__

确实,该函数没有方法__exit__。那么如何使用with语句呢?

4

1 回答 1

3

如果要将 with 语句与函数一起使用,可以使用contextlib.contextmanager装饰器。

文档中的示例:

from contextlib import contextmanager

@contextmanager
def tag(name):
    print "<%s>" % name
    yield
    print "</%s>" % name

>>> with tag("h1"):
...    print "foo"
...
<h1>
foo
</h1>
于 2012-04-28T21:55:58.097 回答