Assign multiple functions to a single variable?

后端 未结 3 579
遇见更好的自我
遇见更好的自我 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
    
    0 讨论(0)
  • 2020-12-06 23:19

    Just create a wrapper function:

    def sin_rad(degrees):
        return math.sin(math.radians(degrees))
    

    Call your wrapper function as normal:

    print sin_rad(my_number_in_degrees)
    
    0 讨论(0)
  • 2020-12-06 23:22

    I think what the author wants is some form of functional chaining. In general, this is difficult, but may be possible for functions that

    1. take a single argument,
    2. return a single value,
    3. the return values for the previous function in the list is of the same type as that of the input type of the next function is the list

    Let us say that there is a list of functions that we need to chain, off of which take a single argument, and return a single argument. Also, the types are consistent. Something like this ...

    functions = [np.sin, np.cos, np.abs]
    

    Would it be possible to write a general function that chains all of these together? Well, we can use reduce although, Guido doesn't particularly like the map, reduce implementations and was about to take them out ...

    Something like this ...

    >>> reduce(lambda m, n: n(m), functions, 3)
    0.99005908575986534
    

    Now how do we create a function that does this? Well, just create a function that takes a value and returns a function:

    import numpy as np 
    
    def chainFunctions(functions):
        def innerFunction(y):
            return reduce(lambda m, n: n(m), functions, y)
        return innerFunction
    
    if __name__ == '__main__':
        functions = [np.sin, np.cos, np.abs]
        ch = chainFunctions( functions )
        print ch(3)
    
    0 讨论(0)
提交回复
热议问题