Assign multiple functions to a single variable?

后端 未结 3 588
遇见更好的自我
遇见更好的自我 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: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)
    

提交回复
热议问题