python中的global,nonlocal关键字

Global

不加global则为局部变量
加了global表示变量指向全局变量

name = "zhangsan"
def run():
    global name
    name = "lisi"
    print(name)
run()

nonlocal

  • nonlocal指向上一级变量
def run():
    x = 1
    def runrun():
        nonlocal x
        x = 2
    runrun()
    print(x)
run()

执行结果为:2

  • 注意:在python中,全局变量全部大写,局部变量则是小写

猜你喜欢

转载自blog.csdn.net/ZenG_xiangt/article/details/81464262