简体   繁体   中英

How to access decorator attributes?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM