4

我将如何编写这样的装饰器。我希望能够在调用装饰器时指定 max_hits 的值(或者可以选择将其省略)。

例如,期望的用途是

@memoize(max_hits=7)
def a(val):
    print val

或者

@memoize
def a(val):
    print val

(使用第一个示例给出了关于不正确参数的错误。)

装饰师:

class memoize:
    """A decorator to cache previosly seen function inputs.

    usage:
        @memoize
        def some_func(..
    """
    def __init__(self, function, max_hits=None):
        self.max_hits = max_hits
        self.function = function
        self.memoized = {}

    def __call__(self, *args, **kwargs):
        key = (args,tuple(kwargs.items()))
        try:
            return self.memoized[key]
        except KeyError:
            self.memoized[key] = self.function(*args,**kwargs)
        return self.memoized[key]
4

2 回答 2

8

您必须创建memoize一个接受可选参数并返回装饰器的函数max_hits(即另一个将函数作为第一个参数的可调用对象);在这种情况下,您可以使用以下两种语法:

@memoize()
def func(x):
    [...]

@memoize(max_hits=7)
def func(x):
    [...]

所以,大概是这样的:

def memoize(max_hits=None):
    """Returns a decorator to cache previosly seen function inputs.

    usage:
    @memoize()
    def some_func(..
    """
    class decorator:
        def __init__(self, function):
            self.max_hits = max_hits
            self.function = function
            self.memoized = {}

        def __call__(self, *args, **kwargs):
            key = (args,tuple(kwargs.items()))
            try:
                return self.memoized[key]
            except KeyError:
                self.memoized[key] = self.function(*args,**kwargs)
            return self.memoized[key]

    return decorator

请注意,这@memoize()会起作用,但您最初想要的@memoize语法不会;在后一种情况下,您正在装饰的函数@memoizememoize作为第一个参数 ( max_hits) 传递给。如果要处理这种情况,可以扩展memoize如下:

def memoize(max_hits=None):
    if callable(max_hits):
        # For sake of readability...
        func = max_hits
        decorator = memoize(max_hits=None)
        return decorator(func)
    [...original implementation follows here...]
于 2011-05-16T13:53:01.593 回答
4

如果你使用的是3.2+,不要自己写,from functools import lru_cache改用

如果要支持无括号版本,最好为函数参数使用哨兵值,而不是自省“错误”参数。那是:

class Memoized(object):
    # As per the memoize definition in the question

# Leave out the "*, " in 2.x, since keyword-only arguments are only in 3.x
from functools import partial
_sentinel = object()
def memoize(_f=_sentinel, *, max_hits=None):
    if _f is _sentinel:
        return partial(Memoized, max_hits=max_hits)
    return Memoized(_f, max_hits=max_hits)
于 2011-05-16T15:02:19.903 回答