高阶函数示例

Higher Order Function Example

这是UCB中CS61A的问题。我知道 a = cake() 将在 terminal.But 中打印为甜菜 a() 的答案是什么?我在 Python tutor 中尝试过,执行此代码后它什么也没显示。 我很困惑为什么当你在终端输入 "a()" 时会得到这样的答案:

sweets
'cake'

在我看来应该是这样的:

beets
sweets
'cake'

非常感谢。 这是我的代码:

    def cake():
        print('beets')
        def pie():
            print('sweets')
            return 'cake'
        return pie
    a = cake()

a 等于被调用函数 cake 的 return 值。 returned 对象是在 cakepie.

中定义的函数

通过调用 cake 函数分配 a 时。

使用此后缀 () 调用 cake 函数。调用函数时,它会逐步执行函数中定义的代码。

函数首先打印出字符串'beets'.

cake 定义了另一个名为 pie 的函数。调用cake时不会调用pie,因为pie只是定义了,并没有调用。

但是cake的return值是函数pie。所以你需要做的就是在pie分配给的变量后面使用调用后缀()

# Define the function `cake`.
def cake():
    print('beets') # Print the string, 'beets'
    def pie(): # Define a function named `pie`
        print('sweets') # `pie` prints the string 'sweets'
        return 'cake' # and returns another string, 'cake'.
    return pie # Return the pie function

# Call `cake`
a = cake() # `a` is equal to the function `pie`

# Calling `a` will call `pie`. 
# `pie` prints the string 'sweets' and returns the string 'cake'
food = a()

# the variable `food` is now equal to the string 'cake'
print(food)

调用a()时打印'cake'的原因。

python 终端打印 'cake' 因为 'cake' 在调用 a 时被 returned 而没有分配给。因此 python 终端通知您该函数调用的 return 值,因为您没有决定存储它的值。