2010-06-19 112 views
3

我认为做是Python中的装饰器,就像调用函数上的函数一样?

@f 
def g(): 
    print 'hello' 

是完全一样的

def g(): 
    print 'hello' 
g=f(g) 

但是,我有这个代码,使用contextlib.contextmanager:

@contextlib.contextmanager 
def f(): 
    print 1 
    yield 
    print 2 
with f: 
    print 3 

其中工程和产量1 3 2

而当我试图陈GE入

def f(): 
    print 1 
    yield 
    print 2 
f=contextlib.contextmanager(f) 
with f: 
    print 3 

我得到AttributeError: 'function' object has no attribute '__exit__'

我缺少什么?在contextlib.contextmanager中是否存在一些黑魔法,还是我误解了装饰者的工作原理?

回答

5

是,装饰是调用函数和分配给返回的值

在这种情况下,错误出现,因为你没有通话功能完全相同,所以正确的代码将

def f(): 
    print 1 
    yield 
    print 2 

f=contextlib.contextmanager(f) 
with f(): 
    print 3 

还我不知道你是否因同样的原因测试的代码,因为你给了装饰代码将失败

@contextlib.contextmanager 
def f(): 
    print 1 
    yield 
    print 2 
with f: 
    print 3 

错误:

with f: 
AttributeError: 'function' object has no attribute '__exit__' 
+0

谢谢!理性的瞬间失效:) – olamundo 2010-06-19 07:47:29