python - 如何在装饰器中注册它装饰的所有功能?

标签 python decorator python-decorators

假设您有以下装饰器。如何修改它以说附加到它修饰的所有函数的某些列表引用?

def memoize(obj):
    cache = obj.cache = {}

    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwargs)
        return cache[args]
    return memoizer

@memoize
def foo(bar):
    return bar ** 3

最佳答案

您可以轻松地在装饰器函数对象上存储一个列表 (memoize.decorated):

_decorated = []

def memoize(obj):
    cache = obj.cache = {}

    # add to the decorated list
    _decorated.append(obj)

    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwargs)
        return cache[args]
    return memoizer

# make the list accessible from the decorator:
memoize.decorated = _decorated

它可以像这样使用:

@memoize
def foo(bar):
    return bar ** 3

print memoize.decorated

作为旁注,您应该考虑存储 WeakRefs in the list ,以避免内存泄漏或对象在没有其他“真实”引用时未被释放。

关于python - 如何在装饰器中注册它装饰的所有功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29926916/

相关文章:

python - Python 中修饰函数和方法之间的行为差​​异

python - 在 python 内存装饰器类中设置 get/set 属性

python - 如何将 @retry 与关键字参数一起使用并传递函数

python - 循环模板的键值 - Django查询

python - 值错误 : Num gradients 1 generated for op name: "mask/Mask"

.net - 在 Windsor 中注册通用装饰器

python - 将惰性求值转换为装饰器 (Python)

带有@语法的python装饰器参数

python - 如何在pygame中移动ASCII字符?

python - 遍历列表长度并创建函数列表