給出以下代碼,我不明白爲什麼f和fib行爲不同。 從巴克利所採取的示例cs61a當然Python高階函數
def fib(n):
if n==1 or n==0:
return n
else:
return fib(n-1) + fib(n-2)
def decor(f):
def counted(*args):
counted.call_count += 1
return f(*args)
counted.call_count = 0
return counted
當我加載代碼到解釋器我得到這樣的輸出:
>>> fib(6)
8
>>> f = decor(fib)
>>> fib = decor(fib)
>>> # f and fib are both vars that represents a decorated fib function
>>> f(6)
8
>>> f.call_count # why 1 ???
1
>>>
>>> fib(6)
8
>>> fib.call_count # 49 calls, that's fine
49
是否意味着fib在全球範圍內是相同的?我假設綁定fib再裝飾(纖維)返回一個新的功能,這是不相關的'舊'纖維,正如f所做的......是什麼特定於python?讓我想我想念一些基本的語言理解。似乎很明顯,rebind fib應該返回f – chenchuk