How to access decorator attributes?

╄→尐↘猪︶ㄣ 提交于 2020-03-22 05:51:55

问题


Is it possible to access decorator attributes in Python 3?

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 ###

回答1:


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)

is equivalent to this:

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

fibonacci = Cache(fibonacci)

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


来源:https://stackoverflow.com/questions/50895659/how-to-access-decorator-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!