尝试将装饰器重写为Class
不能正常工作。我实际的装饰器是:
def check(callback):
def decorator(function):
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
cb_result = callback()
return result
return wrapper
return decorator
我对类格式的处理方法是
class Check(object):
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
def __call__(self, *call_args, **call_kwargs):
function = call_args[0]
return self.__param__call__(function)
def __param__call__(self, function):
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
cb_result = callback()
return result
return wrapper
我希望像这样使用装饰器:
@Check(callback=a_function_callback)
def my_function():
...
将其重写为类时,我的错误是什么,我也一直试图保持向后兼容性(也称为Python 2.7兼容)。
答案 0 :(得分:2)
您应该在callback
类的Check
方法中接受__init__
作为参数,以便您的wrapper
函数实际上可以将其引用为回调函数:>
class Check(object):
def __init__(self, callback):
self.callback = callback
def __call__(self, func):
return self.__param__call__(func)
def __param__call__(self, func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
cb_result = self.callback()
return result
return wrapper