在Python中翻转函数的参数顺序 [英] Flipping a function's argument order in Python
问题描述
如今,我开始学习haskell,在我这样做的同时,我尝试用Python来实现从中吸取的一些想法.但是,我发现这一挑战.您可以在Haskell中编写一个函数,该函数将另一个函数用作参数,并返回参数顺序颠倒返回相同的函数.可以在Python中做类似的事情吗?例如,
Nowadays, I am starting to learn haskell, and while I do it, I try to implement some of the ideas I have learned from it in Python. But, I found this one challenging. You can write a function in Haskell, that takes another function as argument, and returns the same function with it's arguments' order flipped. Can one do similiar thing in Python? For example,
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做到这一点吗?
Can you possibly do this in Python?
推荐答案
您可以使用嵌套函数定义在Python中创建闭包.这样,您就可以创建一个新的函数来颠倒参数顺序,然后调用原始函数:
You can create a closure in Python using nested function definitions. This lets you create a new function that reverses the argument order and then calls the original function:
>>> 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中翻转函数的参数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!