[英]How to access decorator attributes?
Is it possible to access decorator attributes in Python 3?是否可以在 Python 3 中访问装饰器属性?
For example: is it possible to access self.misses
after the call to the decorated fibonacci method?例如:是否可以在调用装饰的斐波那契方法后访问
self.misses
?
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
现在是一个Cache
实例而不是一个函数:
>>> 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
属性:
>>> fibonacci.misses
21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.