在return语句中用作函数调用的python函数参数?

0yycz8jy  于 2021-09-29  发布在  Java
关注(0)|答案(2)|浏览(285)

因此,我在这里遇到了下面的代码,我无法理解return语句是如何工作的。 operation 是函数中的参数 sevenfive 但它在 return 声明。这里发生了什么事?
代码是:

def seven(operation = None):
    if operation == None:
        return 7
    else:
        return operation(7)

def five(operation = None):
    if operation == None:
        return 5
    else:
        return operation(5)

def times(number):
   return lambda y: y * number

edit:following@chepner comment这是它们的调用方式,例如:

print(seven(times(five())))
lrl1mhuk

lrl1mhuk1#

这些方法基本上允许您传递将被调用的函数对象。看这个例子

def square(x):
    return x*x

def five(operation=None):
    if operation is None:
        return 5
    else:
        return operation(5)

我现在可以打电话了 five 并通过 square 作为 operation ```

five(square)
25

cld4siwp

cld4siwp2#

这里发生了什么事?
该代码利用了函数是一等公民的特性 python ,因此函数可以作为函数参数传递。这种能力不是每个人所独有的 python 语言,但如果您习惯了没有该功能的语言,那么一开始可能会令人难以置信。

相关问题