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