![](/img/trans.png)
[英]Python - Passing Functions with Arguments as Arguments in other Functions
[英]passing functions as arguments in other functions python
我有這些函數,並且我遇到錯誤,使用do_twice函數,但是我在調試它時遇到了問題
#!/usr/bin/python
#functins exercise 3.4
def do_twice(f):
f()
f()
def do_four(f):
do_twice(f)
do_twice(f)
def print_twice(str):
print str + 'one'
print str + 'two'
str = 'spam'
do_four(print_twice(str))
調試器錯誤
:!python 'workspace/python/functions3.4.py'
spamone
spamtwo
Traceback (most recent call last):
File "workspace/python/functions3.4.py", line 18, in <module>
do_four(print_twice(str))
File "workspace/python/functions3.4.py", line 9, in do_four
do_twice(f)
File "workspace/python/functions3.4.py", line 5, in do_twice
f()
TypeError: 'NoneType' object is not callable
shell returned 1
問題是表達式print_twice(str)
是通過使用str
調用print_twice
並獲得返回的結果來評估的,*結果就是你作為do_four
的參數傳遞的do_four
。
你需要傳遞給do_four
是一個函數,當調用它時,調用print_twice(str)
。
您可以手動構建此類功能:
def print_twice_str():
print_twice(str)
do_four(print_twice_str)
或者你可以內聯做同樣的事情:
do_four(lambda: print_twice(str))
或者您可以使用高階函數partial
來為您執行此操作:
from functools import partial
do_four(partial(print_twice, str))
partial
的文檔有一個非常好的解釋:
partial()
用於部分函數應用程序,它“凍結”函數的參數和/或關鍵字的某些部分,從而產生具有簡化簽名的新對象。 例如,partial()
可用於創建一個callable,其行為類似於int()
函數,其中base參數默認為2:[snip]basetwo = partial(int, base=2)
*如果您正在考慮“但我沒有返回任何內容,那么None
來自哪里?”:每個函數總是返回Python中的值。 如果您沒有告訴它返回什么,它將返回None
。
do_four(print_twice(str))
傳遞之前首先計算括號中的表達式。 由於print_twice不返回任何內容,因此假定為None
,並且會傳遞該內容。
現在print_twice
返回None
,這最終作為參數傳遞給do_four
。 換句話說,您傳遞函數調用的結果而不是函數調用本身。
相反,你想在lamda函數中包裝該函數調用,如下所示:
do_four(lambda: print_twice(str))
這將把實際的函數調用作為參數傳遞,而不是調用函數並傳遞其結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.