2012-04-28 65 views
0

我在阅读PEP 343并试图举一些例子。但现在对我来说还不是很清楚。特别是因为我有一个错误:Python与声明

>>> 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声明?

+0

是非常有用的文件,因为它调用了'close'自动上'__exit__' – jamylak 2012-04-28 21:56:51

+2

,你会想到什么'和f():打印F()'来完成? – weronika 2012-04-28 22:00:22

回答

3

如果要在函数中使用with语句,可以使用contextlib.contextmanager装饰器。

例如,从doc

from contextlib import contextmanager 

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

>>> with tag("h1"): 
... print "foo" 
... 
<h1> 
foo 
</h1> 
+0

@senderle:这是真的:) – mouad 2012-04-28 21:58:07

+0

问题是“你如何使用with语句?”不是“有没有一个库使用带声明的函数?”。我不知道为什么这个答案被接受。 – 2015-03-04 10:46:00

+0

@ zoogleflatt因为它回答OP X问题http://mywiki.wooledge.org/XyProblem :) – mouad 2015-03-04 13:59:32