Python class decorator arguments

前端 未结 4 1679
走了就别回头了
走了就别回头了 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:34

    I'd rather to include the wrapper inside the class's __call__ method:

    UPDATE: This method has been tested in python 3.6, so I'm not sure about the higher or earlier versions.

    class Cache:
        def __init__(self, max_hits=10, timeout=5):
            # Remove function from here and add it to the __call__
            self.max_hits = max_hits
            self.timeout = timeout
            self.cache = {}
    
        def __call__(self, function):
            def wrapper(*args):
                value = function(*args)
                # saving to cache codes
                return value
            return wrapper
    
    @Cache()
    def double(x):
        return x * 2
    
    @Cache(max_hits=100, timeout=50)
    def double(x):
        return x * 2
    

提交回复
热议问题