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

问题描述

我想可选的参数传递给在python我的课的装饰。
低于code我目前有:

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,超时= 5 在我的 __的init __ 功能),不能正常工作,我得到异常类型错误:__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,超时= 50)通话 __的init __( max_hits = 100,超时= 50),这样你就不会满足函数参数。

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

您可以实现通过该检测功能是否是present的包装方法,你的装饰。如果找到一个函数,它可以返回缓存的对象。否则,它可以返回将被用作装饰包装函数

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

10-10 22:21