您的代码实际上并未将print_word("potato")(“对print_word 的'调用'”)传递给do_n,而是将None 传递给print_word,因为print_word 返回None。这意味着print_word 运行的唯一时间是do_n( print_word("potato") , 5 )。你可以做的是使用functools.partial,它返回一个应用了参数的函数:
from functools import partial
def print_word(word):
print(word)
return # side note: the "return" isn't necessary
def do_n(function , n):
for i in range(n):
function() # call the function
return
do_n( partial(print_word,"potato") , 5)
functools.partial:
返回一个新的部分对象,当它被调用时,它的行为类似于 func
使用位置参数 args 和关键字参数调用
关键字。如果向调用提供更多参数,则它们是
附加到 args。
另一种方法是使用lambda 语句或单独传递参数:
def print_word(word):
print(word)
return # side note: the "return" isn't necessary
def do_n(function , n):
for i in range(n):
function() # call the function
return
do_n(lambda: print_word("potato"), 5) # use the lambda
或者:
def print_word(word):
print(word)
return # side note: the "return" isn't necessary
def do_n(function , n, *args):
for i in range(n):
function(*args) # call the function
return
do_n(print_word, 5, "potato") # pass the argument of print_word as a separate arg