Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的decorator与对函数调用函数完全相同吗?_Python_Decorator_Contextmanager - Fatal编程技术网

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__'