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

Python function argument used as a function call in the return statement?

所以我看到了下面的代码 here,但我无法理解 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

编辑:在@chepner 评论之后,这是它们的称呼方式,例如:

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

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

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

这里发生了什么?

此代码利用函数是 first-class citizens in python,因此函数可以作为函数参数传递。这种能力并非 python 语言所独有,但如果您习惯于没有该功能的语言,最初可能会令人难以置信。