如何访问装饰器属性? [英] How to access decorator attributes?

查看:87
本文介绍了如何访问装饰器属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Python 3中访问装饰器属性?

Is it possible to access decorator attributes in Python 3?

例如:是否可以访问 self.misses

For example: is it possible to access self.misses after the call to the decorated fibonacci method?

class Cache:
    def __init__(self, func):
        self.func = func
        self.cache = {}
        self.misses = 0    
    def __call__(self, *args):
        if not (args in self.cache):
            self.misses += 1
            self.cache[args] = self.func(*args)
        return self.cache[args]

@Cache    
def fibonacci(n):
    return n if n in (0, 1) else fibonacci(n - 1) + fibonacci(n - 2)

fibonacci(20)
### now we want to print the number of cache misses ###


推荐答案

装饰函数(或类,或其他任何东西)时,实际上是用装饰器的返回值替换装饰的对象。这意味着:

When you decorate a function (or class, or anything else), you're actually replacing the decorated object with the return value of the decorator. That means that this:

@Cache    
def fibonacci(n):
    return n if n in (0, 1) else fibonacci(n - 1) + fibonacci(n - 2)

对此:

def fibonacci(n):
    return n if n in (0, 1) else fibonacci(n - 1) + fibonacci(n - 2)

fibonacci = Cache(fibonacci)

因此, fibonacci 现在是 Cache 实例,而不是函数:

Consequently, fibonacci is now a Cache instance and not a function:

>>> fibonacci
<__main__.Cache object at 0x7fd4d8b63e80>

因此,要获取高速缓存未命中的数量,您只需要访问斐波那契缺失属性:

So in order to get the number of cache misses, you just need to access fibonacci's misses attribute:

>>> fibonacci.misses
21

这篇关于如何访问装饰器属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆