高阶函数示例

时间:2017-09-09 02:26:20

标签: python higher-order-functions

这是UCB中CS61A的问题。我知道a = cake()将作为beets打印在终端中。但是()的答案是什么?我在Python教程中尝试过,它在执行此代码后没有显示任何内容。 当你在终端输入“a()”时,我很困惑为什么这样的答案:

sweets
'cake'

在我看来,它应该是这样的:

beets
sweets
'cake'

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

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

1 个答案:

答案 0 :(得分:-1)

a等于被调用函数cake的返回值。返回的对象是cakepie中定义的函数。

通过调用a函数分配cake

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

该功能首先打印出字符串“甜菜”。

cake定义了另一个名为pie的函数。调用pie时不调用cake,因为只定义了派而不调用派。

cake的返回值是函数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)

为什么' cake'在调用a()时打印。

蟒蛇终端打印' cake'因为' cake'在致电a并且未分配时返回。所以python终端通知你该函数调用的返回值,因为你没有决定存储它的值。