python中的decorator与对函数调用函数完全相同吗?
我以为这样做python中的decorator与对函数调用函数完全相同吗?,python,decorator,contextmanager,Python,Decorator,Contextmanager,我以为这样做 @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 当我试图把它变成 def f(): print 1
@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
当我试图把它变成
def f():
print 1
yield
print 2
f=contextlib.contextmanager(f)
with f:
print 3
我得到AttributeError:'function'对象没有属性'\uuu\uu'
我错过了什么?contextlib.contextmanager中是否有一些黑魔法,或者我是否误解了decorator的一般工作方式?是的,decorator与调用函数并分配给返回值完全相同 在这种情况下,错误是因为您没有调用函数,所以正确的代码应该是
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__'