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

前端 未结 9 1972
温柔的废话
温柔的废话 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:23

    For anyone looking at this much later on a safer but heavier workaround is. Without a need to pass variables as parameters.

    def outer():
        a = [1]
        def inner(a=a):
            a[0] += 1
        inner()
        return a[0]
    

提交回复
热议问题