加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python类装饰器参数

发布时间:2020-12-16 23:02:57 所属栏目:Python 来源:网络整理
导读:我试图在 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__
我试图在 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

具有覆盖默认值的参数的第二个装饰器(max_hits = 10,__init__函数中的timeout = 5)不起作用,我得到异常TypeError:__init __()至少有两个参数(3个给定).我尝试了许多解决方案并阅读有关它的文章,但在这里我仍然无法使其工作.

有什么想法来解决吗?谢谢!

解决方法

@Cache(max_hits = 100,timeout = 50)调用__init __(max_hits = 100,timeout = 50),所以你不满足函数参数.

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

class _Cache(object):
    def __init__(self,*args):
        # Here the code returning the correct thing.

# wrap _Cache to allow for deferred calling
def Cache(function=None,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读