Modify bound variables of a closure in Python

前端 未结 8 1993
醉话见心
醉话见心 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:12
    def foo():
        var_a = 2
        var_b = 3
    
        def _closure(x):
                return var_a + var_b + x
    
        return _closure
    
    def bar():
            var_a = [2]
            var_b = [3]
    
            def _closure(x):
                    return var_a[0] + var_b[0] + x
    
    
            def _magic(y):
                var_a[0] = y
    
            return _closure, _magic
    
    localClosureFoo = foo()
    a = localClosureFoo(1)
    print a
    
    
    
    localClosureBar, localClosureBarMAGIC = bar()
    b = localClosureBar(1)
    print b
    localClosureBarMAGIC(0)
    b = localClosureBar(1)
    print b
    
    0 讨论(0)
  • 2020-12-03 03:14

    I've found an alternate answer answer to Greg's, slightly less verbose because it uses Python 2.1's custom function attributes (which conveniently enough can be accessed from inside their own function).

    def foo():
        var_b = 3
    
        def _closure(x):
            return _closure.var_a + var_b + x
    
        _closure.func_dict['var_a'] = 2
        return _closure
    
    
    localClosure = foo()
    
    # Local closure is now "return 2 + 3 + x"
    a = localClosure(1) # 2 + 3 + 1 == 6
    
    # DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
    # ...but what magic? Is this even possible?
    # apparently, it is
    localClosure.var_a = 0
    
    # Local closure is now "return 0 + 3 + x"
    b = localClosure(1) # 0 + 3 +1 == 4
    

    Thought I'd post it for completeness. Cheers anyways.

    0 讨论(0)
提交回复
热议问题