Python class decorator arguments

前端 未结 4 1703
走了就别回头了
走了就别回头了 2020-12-24 14:50

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         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 15:25

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

    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
    

提交回复
热议问题