why this code is printing once "potato" instead than 5 times ?
def print_word(word):
print word
return
def do_n(function , n):
for i in range(n):
function
return
do_n( print_word("potato") , 5 )
Your code is actually not passing print_word("potato")
("the 'call' to the print_word
") to do_n
, but instead it's passing None
since print_word
returns None
. Which means that the only time that print_word
ran was at do_n( print_word("potato") , 5 )
. What you can do instead is use functools.partial
, which returns a function with the args applied to it:
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)
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args.
Another way is to use a lambda
statement or pass the argument separately:
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
Or:
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
To pass a function with arguments, you can either pass the arguments separately, or you can do a 'partial' application of the function, where you lock a number of variables. Here is such as solution to your problem, where I have 'partially' applied all variables. But, the function is still not called until the function()
statement.
from functools import partial
def print_word(word):
print word
return
def do_n(function, n):
for i in range(n):
function()
return
print_potato = partial(print_word, potato)
do_n(print_potato, 5)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.