Flipping a function's argument order in Python

前端 未结 2 1611
被撕碎了的回忆
被撕碎了的回忆 2020-12-31 16:50

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 ca

2条回答
  •  一个人的身影
    2020-12-31 17:21

    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
    

提交回复
热议问题