Python functions with multiple parameter brackets

前端 未结 3 1663
走了就别回头了
走了就别回头了 2020-12-02 22:54

I\'ve been having trouble understanding what h(a)(b) means. I\'d never seen one of those before yesterday, and I couldn\'t declare a function this way:

3条回答
  •  旧巷少年郎
    2020-12-02 23:44

    Lets say we have an expression like

    f(a)(b)
    

    then, f(a) returns a function itself which gets invoked with argument b. Consider the following example

    def f(a):
       def g(b):
          return a * b
       return g
    

    Then f(5)(4) evaluates to 5 * 4, since f(5) returns a function which is basically

    def g(b):
       return 5 * b
    

    One could now do stuff like this

    mult_by_5 = f(5)
    [mult_by_5(x) for x in range(10)]
    

    Let's be fancy, what about more nested functions?:

    def f(a):
      def g(b):
        def h(c):
          return a * b *c
        return h
      return g
    f(2)(3)(4) # 24
    

提交回复
热议问题