Modify bound variables of a closure in Python

前端 未结 8 2018
醉话见心
醉话见心 2020-12-03 02:14

Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.

def foo():
    var_a = 2
           


        
8条回答
  •  时光取名叫无心
    2020-12-03 03:07

    Why not make var_a and var_b arguments of the function foo?

    def foo(var_a = 2, var_b = 3):
        def _closure(x):
            return var_a + var_b + x
        return _closure
    
    localClosure = foo() # uses default arguments 2, 3
    print localClosure(1) # 2 + 3 + 1 = 6
    
    localClosure = foo(0, 3)
    print localClosure(1) # 0 + 3 + 1 = 4
    

提交回复
热议问题