Python 类装饰器参数 [英] Python class decorator arguments

查看:33
本文介绍了Python 类装饰器参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to pass optional arguments to my class decorator in python. Below the code I currently have:

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, timeout=5 在我的 __init__ 函数中)不起作用,我得到了异常 TypeError: __init__() 需要至少 2 个参数(给定 3 个).我尝试了很多解决方案并阅读了有关它的文章,但在这里我仍然无法使其工作.

The second decorator with arguments to overwrite the default one (max_hits=10, timeout=5 in my __init__ function), is not working and I got the exception TypeError: __init__() takes at least 2 arguments (3 given). I tried many solutions and read articles about it, but here I still can't make it work.

有什么办法可以解决这个问题吗?谢谢!

Any idea to resolve this? Thanks!

推荐答案

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

@Cache(max_hits=100, timeout=50) calls __init__(max_hits=100, timeout=50), so you aren't satisfying the function argument.

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

You could implement your decorator via a wrapper method that detected whether a function was present. If it finds a function, it can return the Cache object. Otherwise, it can return a wrapper function that will be used as the decorator.

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 类装饰器参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆