【发布时间】:2018-07-15 19:43:15
【问题描述】:
我是 Python 的初学者,正在从 Lutz 的书中学习装饰器。我在下面遇到了这段代码。我不确定tracer 为何以及如何保留函数调用的数量,即使创建了新实例也是如此。
class tracer:
def __init__(self,func):
self.calls=0
self.func=func
def __call__(self, *args):
self.calls+=1
print('call %s to %s' %(self.calls,self.func.__name__))
self.func(*args)
@tracer
def spam(a,b,c):
print (a+b+c)
spam(1,2,3) #Here calls counter increments to 1
t= tracer(spam)
t.func(3,4,5) # here calls counter increments to 2 even though I called `spam` using new instance `t`
g=tracer(spam)
g.func(4,5,6) #calls counter increments to 3.
正如我们在上面看到的,即使创建了一个新实例,calls 计数器状态也会保留。
有人能解释一下为什么会这样吗?我尝试使用 PyCharm 调试代码,似乎spam 的内存位置保持不变,与特定实例的调用无关。
我正在使用 Anaconda Distribution 中的 Python 3.6。
【问题讨论】:
标签: python python-3.x decorator python-decorators