gpt4 book ai didi

python - python函数中的奇怪返回值

转载 作者:行者123 更新时间:2023-11-28 20:58:12 25 4
gpt4 key购买 nike

def cons(a, b):
def pair(f):
return f(a, b)
return pair

def car(f):
def left(a, b):
return a
return f(left)

def cdr(f):
def right(a, b):
return b
return f(right)

在 git 上找到了这段 python 代码。

只是想知道 cons 定义中的 f(a,b) 是什么,它是如何工作的?(我猜不是函数)

最佳答案

cons 是一个函数,它接受两个参数,并返回一个接受另一个函数的函数,该函数将使用这两个参数。

例如,考虑以下函数:

def add(a, b):
return a + b

这只是一个将两个输入相加的函数,例如,add(2, 5) == 7

由于这个函数有两个参数,我们可以使用 cons 来调用这个函数:

func_caller = cons(2, 5)  # cons receives two arguments and returns a function, which we call func_caller

result = func_caller(add) # func_caller receives a function, that will process these two arguments

print(result) # result is the actual result of doing add(2, 5), i.e. 7

这种技术对于包装函数和执行东西很有用,之前之后调用适当的函数。

例如,我们可以修改我们的 cons 函数来实际打印调用 add 前后的值:

def add(a, b):
print('Adding {} and {}'.format(a, b))
return a + b


def cons(a, b):
print('Received arguments {} and {}'.format(a, b))
def pair(f):
print('Calling {} with {} and {}'.format(f, a, b))
result = f(a, b)
print('Got {}'.format(result))
return result
return pair

通过这次更新,我们得到以下输出:

 func_caller = cons(2, 5)
# prints "Received arguments 2 and 5" from inside cons

result = func_caller(add)
# prints "Calling add with 2 and 5" from inside pair
# prints "Adding 2 and 5" from inside add
# prints "Got 7" from inside pair

关于python - python函数中的奇怪返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51970151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com