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

yas*_*sar 9 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
Run Code Online (Sandbox Code Playgroud)

你能用Python做到这一点吗?

Ray*_*ger 16

您可以使用嵌套函数定义在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
Run Code Online (Sandbox Code Playgroud)

  • @ thg435只是在'flip`的定义上.这种冗长是*好*冗长的恕我直言,因为它使内部翻转的内容显而易见. (2认同)
  • 为什么这不存在于functools中呢? (2认同)
  • 即使不添加 @wraps 装饰器,该解决方案也应该有效。 (2认同)

geo*_*org 14

纯粹的功能风格:

flip = lambda f: lambda *a: f(*reversed(a))

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

print flip(divide)(3.0, 1.0)
Run Code Online (Sandbox Code Playgroud)

更有趣的例子:

unreplace = lambda s: flip(s.replace)

replacements = ['abc', 'XYZ']
a = 'abc123'
b = a.replace(*replacements)
print b
print unreplace(b)(*replacements) # or just flip(b.replace)(*replacements)
Run Code Online (Sandbox Code Playgroud)