【问题标题】:Add method to decorator in Python在 Python 中为装饰器添加方法
【发布时间】:2020-02-19 09:02:04
【问题描述】:

在关于lru_cachethis 文档中,我可以看到可以使用点符号调用装饰器上的函数,例如我可以调用:

lru_cache_decorated_func.cache_info()

我想要实现的是使用我的自定义函数制作我自己的装饰器来调用它,并且像cache_info() 一样调用它。

那么我怎样才能将这样的功能添加到装饰器中呢?

【问题讨论】:

    标签: python decorator python-decorators


    【解决方案1】:

    装饰器只不过是返回 callable[0] aka 的可调用对象

    @foo
    def bar():
       ...
    

    完全一样:

    def bar():
        ...
    bar = foo(bar)
    

    “智能”装饰器有多种选择,lru_cache 的作用非常简单:

    • 它将装饰函数包装在 wrapper 函数中
    • 然后将其设置为 wrapper 函数的属性
    • 它返回包装器(交换包装器的原始函数)
    import functools
    
    def foo(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            return fn(*args, **kwargs)
        wrapper.thing = 'yay'
        return wrapper
    
    @foo
    def bar(): ...
    
    print(bar.thing)
    

    将打印yay

    [0] 甚至是不可调用的,例如 @property@cached_property

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 2021-04-12
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多