相关疑难解决方法(0)

Python functools.wraps等同于类

使用类定义装饰器时,如何自动转移__name__,__module____doc__?通常,我会使用functools的@wraps装饰器.这是我为一个课而做的(这不完全是我的代码):

class memoized:
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated.
    """
    def __init__(self, func):
        super().__init__()
        self.func = func
        self.cache = {}

    def __call__(self, *args):
        try:
            return self.cache[args]
        except KeyError:
            value = self.func(*args)
            self.cache[args] = value
            return value
        except TypeError:
            # uncacheable -- for instance, passing a list as an argument.
            # Better to not …
Run Code Online (Sandbox Code Playgroud)

python decorator

69
推荐指数
4
解决办法
2万
查看次数

标签 统计

decorator ×1

python ×1