2017-01-30 113 views
2

我正在學Python,並且正在閱讀「Think Python」,並在本書中做了一些簡單的練習。Python中的函數給出了錯誤信息

我被問到:「定義一個名爲do_four的新函數,它接受一個函數對象和一個值,然後調用該函數四次,並將該值作爲參數傳遞。

我想通過調用一個已經定義的函數do_tice()並用一個名爲print_double()的函數來用一個語句來編寫這個函數。下面是代碼:

def do_twice(f, x): 
    f(x) 
    f(x) 

def do_four(f, v): 
    do_twice(do_twice(f, v), v) 

def print_twice(s): 
    print s 
    print s 

s = 'abc' 

do_four(print_twice, s) 

此代碼產生一個錯誤:

abc 
abc 
abc 
abc 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-41-95b513e5e0ee> in <module>() 
----> 1 do_four(print_twice, s) 

<ipython-input-40-100f8587f50a> in do_four(f, v) 
     1 def do_four(f, v): 
----> 2  do_twice(do_twice(f, v), v) 

<ipython-input-38-7143620502ce> in do_twice(f, x) 
     1 def do_twice(f, x): 
----> 2  f(x) 
     3  f(x) 

TypeError: 'NoneType' object is not callable 

在試圖瞭解發生了什麼事我試圖構建一個棧圖在書中描述的。那就是:

enter image description here

你能解釋一下在棧圖錯誤消息和評論?

您的建議將不勝感激。

回答

2

do_twice獲取第一個參數的函數,並且不返回任何東西。所以沒有理由通過do_twicedo_twice的結果。你需要通過它a function

這會做你的意思:

def do_four(f, v): 
    do_twice(f, v) 
    do_twice(f, v) 

非常相似,你如何f

定義 do_twice
1
do_twice(do_twice(f, v), v) 
     ^^^^^^^^^^^^^^ 

稍微改寫:

result = do_twice(f, v) 
do_twice(result, v) 

要傳遞的do_twice(...)返回值作爲第一個參數來do_twice(...)。該參數應該是一個函數對象。 do_twice不會返回任何東西,所以resultNone,您正在傳遞,而不是預期的函數對象。

在這裏以任何方式嵌套兩個do_twice毫無意義。

0
do_twice(do_twice(f, v), v) 

您不能將do_twice(f,v)作爲函數參數傳遞,因爲它不返回任何內容。