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

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

    You can, but you'll have to use the global statment (not a really good solution as always when using global variables, but it works):

    def A():
        global b
        b = 1
    
        def B():
          global b
          print( b )
          b = 2
    
        B()
    A()
    

提交回复
热议问题