2016-07-23 192 views
1

給出以下代碼,我不明白爲什麼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 

回答

2

f.call_count是1,因爲f呼叫fib,然後fib遞歸調用自身來計算結果。在這整個過程中,f只被調用一次。

但是當你做fib = decor(fib),你覆蓋fib功能在全球範圍內,所以從那一刻起fib會遞歸調用裝飾fib

0

您將要覆蓋fib然後f電話fib,而不是本身:在0x7fa844639758

=== f === 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
8 
1 
=== fib === 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
fib is: <function counted at 0x7fa844639758> 
8 
49 

注意fib is功能的所有時間:

def fib(n): 
    if n==1 or n==0: 
     return n 
    else: 
     print("fib is: " + repr(fib)) 
     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 



f = decor(fib) 
fib = decor(fib) 

print("=== f ===") 
print(f(6)) 
print(f.call_count) 

print("=== fib ===") 
print(fib(6)) 
print(fib.call_count) 

當我運行這個輸出。

+0

是否意味着fib在全球範圍內是相同的?我假設綁定fib再裝飾(纖維)返回一個新的功能,這是不相關的'舊'纖維,正如f所做的......是什麼特定於python?讓我想我想念一些基本的語言理解。似乎很明顯,rebind fib應該返回f – chenchuk