Is it possible to modify variable in python that is in outer, but not global, scope?

前端 未结 9 1967
温柔的废话
温柔的废话 2020-11-30 02:55

Given following code:

def A() :
    b = 1

    def B() :
        # I can access \'b\' from here.
        print( b )
        # But can i modify \'b\' here? \'         


        
9条回答
  •  悲&欢浪女
    2020-11-30 03:16

    Python 3.x has the nonlocal keyword. I think this does what you want, but I'm not sure if you are running python 2 or 3.

    The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

    For python 2, I usually just use a mutable object (like a list, or dict), and mutate the value instead of reassign.

    example:

    def foo():
        a = []
        def bar():
            a.append(1)
        bar()
        bar()
        print a
    
    foo()
    

    Outputs:

    [1, 1]
    

提交回复
热议问题