return函数在下面的函数中有什么作用?

What does return function do in the functions below?

你能给我解释一下 callsquared_callreturn 函数有什么作用吗?

def mult_by_five(x):
    return 5 * x

def call(fn, arg):
    """Call fn on arg"""
    return fn(arg)

def squared_call(fn, arg):
    """Call fn on the result of calling fn on arg"""
    return fn(fn(arg))

print(
    call(mult_by_five, 1),
    squared_call(mult_by_five, 1), 
    sep='\n', # '\n' is the newline character - it starts a new line
)

如果你退后一步,代入不同的功能,这会更有意义。

而不是 return fn(fn(n)),请查看更简单的示例。

return int(n)

这 return 是 int(n) 的结果。 n 传递给 int,然后 int returns 是 returned.

return str(int(n))

这 return 是 str(int(n)) 的结果。 n 传递给 int,然后 int returns 传递给 str,然后 str returns 传递给 str returns returned.

该示例中的困难部分是 fn 是作为参数传递给 callsquared_call 的函数。

当你写call(mult_by_five, 1)时,call中的return行相当于:

return mult_by_five(1)

当你写squared_call(mult_by_five, 1)时,squared_call中的return行相当于:

return mult_by_five(mult_by_five(1))