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
当我尝试将其更改为时,
def f():
print 1
yield
print 2
f=contextlib.contextmanager(f)
with f:
print 3
我得到了 AttributeError : 'function' 对象没有属性 '__exit__'
我缺少什么? contextlib.contextmanager 中是否有一些黑魔法,或者我是否误解了装饰器的一般工作原理?
I thought that doing
@f
def g():
print 'hello'
is exactly the same as
def g():
print 'hello'
g=f(g)
But, I had this code, that uses contextlib.contextmanager:
@contextlib.contextmanager
def f():
print 1
yield
print 2
with f:
print 3
which works and yields 1 3 2
And when I tried to change it into
def f():
print 1
yield
print 2
f=contextlib.contextmanager(f)
with f:
print 3
I get AttributeError: 'function' object has no attribute '__exit__'
What am I missing? is there some black magic specifically in contextlib.contextmanager, or do i misunderstand how decorators work in general?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,装饰器与调用函数并分配给返回值完全相同
在这种情况下会出现错误,因为您没有调用函数,所以正确的代码
也是我不确定您是否测试了代码,因为您给出的装饰器代码将失败由于同样的原因
错误:
Yes, decorator is exactly same as calling a function and assigning to returned value
In this case error comes because you are not calling function, so correct code would be
also I am not sure if you tested code, because decorator code you have given will fail due to same reason
Error: