gpt4 book ai didi

Python:为什么我不能让我的装饰器工作?

转载 作者:太空宇宙 更新时间:2023-11-03 23:50:15 27 4
gpt4 key购买 nike

现在这对那些刚接触这个问题的人有效:

class ensureparams(object):
"""

Used as a decorator with an iterable passed in, this will look for each item
in the iterable given as a key in the params argument of the function being
decorated. It was built for a series of PayPal methods that require
different params, and AOP was the best way to handle it while staying DRY.


>>> @ensureparams(['name', 'pass', 'code'])
... def complex_function(params):
... print(params['name'])
... print(params['pass'])
... print(params['code'])
>>>
>>> params = {
... 'name': 'John Doe',
... 'pass': 'OpenSesame',
... #'code': '1134',
... }
>>>
>>> complex_function(params=params)
Traceback (most recent call last):
...
ValueError: Missing from "params" dictionary in "complex_function": code
"""
def __init__(self, required):
self.required = set(required)

def __call__(self, func):
def wrapper(*args, **kwargs):
if not kwargs.get('params', None):
raise KeyError('"params" kwarg required for {0}'.format(func.__name__))
missing = self.required.difference(kwargs['params'])
if missing:
raise ValueError('Missing from "params" dictionary in "{0}": {1}'.format(func.__name__, ', '.join(sorted(missing))))
return func(*args, **kwargs)
return wrapper

if __name__ == "__main__":
import doctest
doctest.testmod()

最佳答案

def wrapper(params): 意味着您只会接受一个参数——因此当然调用 (self, params) 是不会的工作。您需要能够接受一个或两个参数,例如,至少(如果您不需要支持带有命名参数的调用):

def wrapper(one, two=None):
if two is None: params = one
else: params = two
# and the rest as above

为了也接受命名参数,您可以变得更加复杂/复杂,但这要简单得多并且仍然“大部分有效”;-)。

关于Python:为什么我不能让我的装饰器工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2039699/

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