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

标签 python functional-programming

现在,我开始学习 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/

相关文章:

python - 无法运行 Enthought python

python - 根据交集在列表中查找最佳超集

typescript - Typescript能够执行简单的功能组合吗?

haskell - 如何在绑定(bind)中使用 let 或 where 语句

javascript - 将 Function.prototype.bind 与参数数组一起使用?

python - 如何在 Pandas 列中查找并提取字符串的一部分并将其编码到新列中

python - 动态 ChoiceField 无法在表单中进行验证

javascript - 通过将参数包装在函数中来延迟评估?

functional-programming - 在 LISP 中是否可以访问函数的形式?

python - 如何在 Python 中查看某个时间点何时过去