我有一个装饰器来注册一些类方法。如何正确获取self
和run
参数?
class Task(object):
_tasks = []
@staticmethod
def register(name):
def decorator(fn):
@wraps(fn)
def wrapper(self=None, run=True, *args, **kwargs):
if not run:
task = defaultdict()
task['name'] = name
task['fn'] = getattr(self, fn.__name__, None)
task['obj'] = self
task['args'] = deepcopy(args)
task['kwargs'] = deepcopy(kwargs)
Task._tasks.append(task)
else:
return fn(self, *args, **kwargs)
return wrapper
return decorator
class Test(object):
def __init__(self, name):
self.name = name
@Task.register('foo')
def foo(self, v1, v2):
print 'running foo in object {} with arguments {} {}'.format(self.name, v1, v2)
@Task.register('hello')
def hello(self):
print 'running hello in object {} '.format(self.name)
def load(self):
self.foo('1', '2', run=False)
self.hello(run=False)
t1=Test('t1')
t1.load()
出现了以下错误:
Traceback (most recent call last):
TypeError: wrapper() got multiple values for keyword argument 'run'
from functools import *
) - user202729