我以为做

@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' object has no attribute '__exit__'

我想念什么?在ContextLib.ContextManager中是否有一些黑魔法,还是我误会了装饰者的一般工作方式?

有帮助吗?

解决方案

是的,装饰器与调用功能并分配给返回值完全相同

在这种情况下,错误是因为您没有调用功能,因此正确的代码将是

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__'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top