[英]What is the correct way to define a python decorator in a class?
What I'd like to achieve is that the following code out puts the following: 我想要实现的是,下面的代码放出了以下内容:
I'm wondering if my use of __call__ is somehow clobbering functools.wraps; 我想知道我使用__call__是否以某种方式破坏了functools.wraps; it also appears that the arguments are lost at some point. 在某些时候似乎也失去了论点。
Is what I'm trying to achieve possible? 我要实现的目标有可能吗?
from functools import wraps
class Decorator():
def __init(self, something=None):
self.something = something
def __call__(self, func):
print 'Here1'
@wraps(func)
def _wrapper(*args, **kwargs):
return self.call(func, *args, **kwargs)
return _wrapper
def call(self, func, *args, **kwargs):
print 'Here2'
retsult = func(*args, **kwargs)
return result
if __name__ == '__main__':
decorator = Decorator()
@decorator
def do_the_thing(arg1='argOne', arg2='argTwo'):
print 'Here3 {0} {1}'.format(arg1, arg2)
return
Seems you just had a few typos and weren't actually calling the function do_the_thing
. 似乎您只是有一些错别字,实际上并没有调用函数do_the_thing
。
Changed it to this and worked just fine. 将其更改为此并可以正常工作。
from functools import wraps
class Decorator():
def __init__(self, something=None): # you are missing the __ on the right
self.something = something
def __call__(self, func):
print 'Here1'
@wraps(func)
def _wrapper(*args, **kwargs):
return self.call(func, *args, **kwargs)
return _wrapper
def call(self, func, *args, **kwargs):
print 'Here2'
result = func(*args, **kwargs) # result was misspelled
return result
if __name__ == '__main__':
@Decorator() # Just a bit cleaner
def do_the_thing(arg1='argOne', arg2='argTwo'):
print 'Here3 {0} {1}'.format(arg1, arg2)
do_the_thing() # func was never called.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.