Assign multiple functions to a single variable?

后端 未结 3 590
遇见更好的自我
遇见更好的自我 2020-12-06 22:40

In Python we can assign a function to a variable. For example, the math.sine function:

sin = math.sin
rad = math.radians
print sin(rad(my_number_in_degrees))         


        
3条回答
  •  天命终不由人
    2020-12-06 23:18

    You could write a helper function to perform the function composition for you and use it to create the kind of variable you want. Some nice features are that it can combine a variable number of functions together that each accept a variable number of arguments.

    import math
    try:
        reduce
    except NameError:  # Python 3
        from functools import reduce
    
    def compose(*funcs):
        """ Compose a group of functions (f(g(h(...)))) into a single composite func. """
        return reduce(lambda f, g: lambda *args, **kwargs: f(g(*args, **kwargs)), funcs)
    
    sindeg = compose(math.sin, math.radians)
    
    print(sindeg(90))  # -> 1.0
    

提交回复
热议问题