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

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

    I'm a little new to Python, but I've read a bit about this. I believe the best you're going to get is similar to the Java work-around, which is to wrap your outer variable in a list.

    def A():
       b = [1]
       def B():
          b[0] = 2
       B()
       print(b[0])
    
    # The output is '2'
    

    Edit: I guess this was probably true before Python 3. Looks like nonlocal is your answer.

提交回复
热议问题