True dynamic and anonymous functions possible in Python?

前端 未结 7 1462
说谎
说谎 2020-11-28 05:34

Just as a dynamic class can be created using type(name, base-classes, namespace-dict), can a dynamic function be created?

I\'ve tried doing something along the line

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 05:54

    A lot of people seem to be misled about the purpose of “lambda” in Python: its sole purpose is to define a simple single-expression function without a name. Nothing more. In Python, functions are indeed first-class objects, like they are in, say, LISP: you can pass them as arguments, store them in data structures, and return them as results. For example, here is a function that composes two given functions f and g, so compose(f, g)(x) is equivalent to f(g(x)):

    def compose(f, g) :
        def result(x) :
            return f(g(x))
        #end result
        return result
    #end compose
    

    and here’s an example use:

    >>> h = compose(lambda x : x + 2, lambda x : x * x)
    >>> h(3)
    11
    

提交回复
热议问题