nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量

在内层函数中只可以读,但是不可以修改

 

a = 100
def Outer():
    b = 10

    def Inner():
        nonlocal b #声明外部函数的局部变量,
        print('inner b:',b) # 只可以读取使用,但是不可以修改,如果想修改必须上面语句声明一下。下面的global也是
        b = 20     

        global a  
        a = 1000

    Inner()
    print("outer b:",b)

Outer()
print("a:",a)

 

相关文章:

  • 2021-11-25
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-02
  • 2021-12-26
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-05
  • 2022-12-23
  • 2022-12-23
  • 2021-05-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案