gpt4 book ai didi

Python 类装饰器参数

转载 作者:太空狗 更新时间:2023-10-29 17:24:01 25 4
gpt4 key购买 nike

我正在尝试将可选参数传递给我的 python 类装饰器。在我目前拥有的代码下方:

class Cache(object):
def __init__(self, function, max_hits=10, timeout=5):
self.function = function
self.max_hits = max_hits
self.timeout = timeout
self.cache = {}

def __call__(self, *args):
# Here the code returning the correct thing.


@Cache
def double(x):
return x * 2

@Cache(max_hits=100, timeout=50)
def double(x):
return x * 2

第二个带有覆盖默认装饰器参数的装饰器(__init__ 函数中的max_hits=10, timeout=5)不起作用,我得到了异常TypeError: __init__() takes at least 2 arguments (3 given).我尝试了很多解决方案并阅读了有关它的文章,但在这里我仍然无法使其工作。

有解决这个问题的想法吗?谢谢!

最佳答案

@Cache(max_hits=100, timeout=50) 调用 __init__(max_hits=100, timeout=50),所以您不满足 函数参数。

您可以通过检测函数是否存在的包装方法来实现您的装饰器。如果它找到一个函数,它可以返回 Cache 对象。否则,它可以返回一个将用作装饰器的包装函数。

class _Cache(object):
def __init__(self, function, max_hits=10, timeout=5):
self.function = function
self.max_hits = max_hits
self.timeout = timeout
self.cache = {}

def __call__(self, *args):
# Here the code returning the correct thing.

# wrap _Cache to allow for deferred calling
def Cache(function=None, max_hits=10, timeout=5):
if function:
return _Cache(function)
else:
def wrapper(function):
return _Cache(function, max_hits, timeout)

return wrapper

@Cache
def double(x):
return x * 2

@Cache(max_hits=100, timeout=50)
def double(x):
return x * 2

关于Python 类装饰器参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7492068/

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