我想計算給定函數被調用的次數。訪問在裝飾器之外的裝飾器中創建的函數屬性
所以,我做了一個countcalls
修飾器給我的功能__callcount
屬性,每增加一個電話。夠簡單。
我的問題是得到__callcount
值後面退出。
這裏是我的代碼:
import functools
def countcalls(f):
f.__callcount = 0
@functools.wraps(f)
def _countcalls(*args, **kwds):
f.__callcount += 1
print(' Called {0} time(s).'.format(f.__callcount))
return f(*args, **kwds)
return _countcalls
@countcalls
def fib(n):
if n < 0:
raise ValueError('n must be > 0')
if n == 0 or n == 1:
return 1
return fib(n-1) + fib(n-2)
if __name__ == '__main__':
print('Calling fib(3)...')
x = fib(3)
print('fib(3) = {0}'.format(x))
print('Calling fib(3) again...')
x = fib(3)
print('fib(3) = {0}'.format(x))
print('fib was called a total of {0} time(s).'.format(fib.__callcount))
產生以下輸出(Python的3.3.0):
Calling fib(3)...
Called 1 time(s).
Called 2 time(s).
Called 3 time(s).
Called 4 time(s).
Called 5 time(s).
fib(3) = 3
Calling fib(3) again...
Called 6 time(s).
Called 7 time(s).
Called 8 time(s).
Called 9 time(s).
Called 10 time(s).
fib(3) = 3
fib was called a total of 0 time(s).
爲什麼在最後一行fib.__callcount
等於0
?如輸出所示,__callcount
得到遞增,並在fib
的調用之間持續存在。
我錯過了什麼?
我認爲這是一個範圍/上下文問題。 http://stackoverflow.com/a/1753475/2823755可能會解釋此行爲。 – wwii
好找。我只是嘗試使用'setattr(f,'__callcount',0)'和'getattr(f,'__callcount')',但它們表現出與原始行爲完全相同的行爲。 'f .__ dict __ ['__ callcount']'也是同樣的行爲。 – Keeler