我想要实现的是下面的代码输出以下内容:
- Here1
- Here2
我想知道我对__call__的使用是否在某种程度上破坏了functools.wraps;从某种程度上看,这些论点似乎是失败的。
我想要达到的是可能的吗?
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
似乎你只是有几个打字错误,实际上并没有调用函数do_the_thing
。
改成这个,效果很好。
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.