gpt4 book ai didi

python - 在 Python 中翻转函数的参数顺序

转载 作者:太空狗 更新时间:2023-10-29 20:33:53 28 4
gpt4 key购买 nike

现在,我开始学习 haskell,在学习的同时,我尝试用 Python 实现我从中学到的一些想法。但是,我发现这具有挑战性。你可以在 Haskell 中编写一个函数,它接受另一个函数作为参数,并返回相同的函数,但它的参数顺序被翻转了。可以用 Python 做类似的事情吗?例如,

def divide(a,b):
return a / b

new_divide = flip(divide)

# new_divide is now a function that returns second argument divided by first argument

你能用 Python 做到这一点吗?

最佳答案

您可以使用嵌套函数定义在 Python 中创建闭包。这使您可以创建一个颠倒参数顺序的新函数,然后调用原始函数:

>>> from functools import wraps
>>> def flip(func):
'Create a new function from the original with the arguments reversed'
@wraps(func)
def newfunc(*args):
return func(*args[::-1])
return newfunc

>>> def divide(a, b):
return a / b

>>> new_divide = flip(divide)
>>> new_divide(30.0, 10.0)
0.3333333333333333

关于python - 在 Python 中翻转函数的参数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850259/

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