【问题标题】:Higher Order Function Example高阶函数示例
【发布时间】:2017-09-09 02:26:20
【问题描述】:

这是UCB中CS61A的问题。我知道 a = cake() 将在终端打印为甜菜。但是 a() 的答案是什么?我在 Python 导师中尝试过,执行此代码后它什么也没显示。 我很困惑为什么在终端中输入“a()”时会出现这样的答案:

sweets
'cake'

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

beets
sweets
'cake'

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

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

【问题讨论】:

  • a() 调用 pie 不记录 beets
  • 这是否意味着“print('beets')”还没有被执行?

标签: python higher-order-functions


【解决方案1】:

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

通过调用cake 函数分配a

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

该函数首先打印出字符串“甜菜”。

cake 定义了另一个名为pie 的函数。调用cake 时不会调用pie,因为仅定义了饼图而不调用。

但是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)

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

python 终端打印 'cake' 因为调用 a 时返回了 'cake' 并且没有分配给。因此,python 终端会通知您该函数调用的返回值,因为您没有决定存储它的值。

【讨论】:

  • 我同意你的观点,但是为什么“print('beets')”没有被执行?
  • beets 仅在调用 cake() 时打印,而不是 pie() (a=pie)
  • 非常感谢,我意识到该作业右侧的 cake() 只会返回“cake”。所以'a'是'pie'函数,它打印'sweets'并返回'None'并将'cake'分配给'a'。
  • 在这种情况下,函数cake()的返回是未被调用的函数pie。你通过调用cake的返回分配的变量来调用pie。
猜你喜欢
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
相关资源
最近更新 更多