gpt4 book ai didi

python 类方法的装饰器

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:29 24 4
gpt4 key购买 nike

我有一个装饰器来注册一些类方法。如何正确获取 selfrun 参数?

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'

最佳答案

您的问题与装饰器无关。您的代码实际上执行与此相同的操作:

def foo(run=False, *args, **kwargs):
print(run, args, kwargs)

foo(1, 2, run=True) # TypeError: foo() got multiple values for argument 'run'

根据函数的签名,Python 将尝试设置 run=1args = (2,),然后遇到 TypeError .

一个修复 - 虽然不是一个很好的修复 - 可能是:

def foo(*args, **kwargs):
run = kwargs.pop('run', False) # run defaults to False; remove from kwargs
print(run, args, kwargs)

关于python 类方法的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48616888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com