Python 高阶函数示例
这是UCB中CS61A的一个问题。我知道a=cake将在终端中以甜菜的形式打印出来。但是a的答案是什么?我在Python tutor中尝试过,执行此代码后,它什么也没有显示。 我不明白为什么在终端中输入时会出现这样的答案:Python 高阶函数示例,python,higher-order-functions,Python,Higher Order Functions,这是UCB中CS61A的一个问题。我知道a=cake将在终端中以甜菜的形式打印出来。但是a的答案是什么?我在Python tutor中尝试过,执行此代码后,它什么也没有显示。 我不明白为什么在终端中输入时会出现这样的答案: sweets 'cake' 在我看来,应该是这样的: beets sweets 'cake' 非常感谢。 这是我的代码: def cake(): print('beets') def pie(): print
sweets
'cake'
在我看来,应该是这样的:
beets
sweets
'cake'
非常感谢。
这是我的代码:
def cake():
print('beets')
def pie():
print('sweets')
return 'cake'
return pie
a = cake()
a等于被调用函数的返回值。返回的对象是在cake,pie中定义的函数
当通过调用cake函数来分配时
通过使用此后缀调用cake函数。调用函数时,它将逐步遍历函数中定义的代码
函数首先打印出字符串“beets”
cake定义了另一个名为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时打印“蛋糕”的原因。
python终端打印“cake”,因为“cake”是在调用时返回的,并且没有分配给。因此python终端通知您该函数调用的返回值,因为您没有决定存储其值 a称之为不记录甜菜的馅饼。这是不是意味着打印“甜菜”还没有执行?我同意你的观点,但为什么打印“甜菜”还没有执行?甜菜只在调用蛋糕时打印,而不是馅饼a=馅饼非常感谢,我意识到该作业右侧的蛋糕只会返回“蛋糕”。因此,“a”是“pie”函数,它打印“sweets”,返回“None”,并将“cake”赋值给“a”。在本例中,函数cake的返回是未调用的函数pie。通过调用蛋糕返回所分配的变量来调用pie。