《原创》python中的作用域和global使用上的区别

# coding:utf-8
# 2022年5月10日 陈眺
# 变量作用域和global使用对比
n = 0
def test2():
    global m
    print('test2, i: ', i) # test2, i: 1
    print('test2, m: ', m) #如果不在test1中加入global m,就会报错NmaeError:name 'm' is not defined
    m = 4 # 如果不在test2中加入global m,会报错:unboundlocalerror:local variable 'm' referenced before assignment

def test1():
    print('test1, i:', i) #test1, i: 1
    global n, m
    n = 2
    m = 2
    test2()
    print('m: ', m) #4

if __name__ == '__main__':
    i = 1
    test1()
    print('n: ', n) #如果在test1中不加入global n,输出结果为0,加了就输出2
    # 总结以上i可以在各个方法中读取
    # 方法a中调用方法b,方法a中的变量无法在方法b中读取
    # 方法a中调用方法b,如果想在方法b中读取a中的变量,必须在a中使用global;如果想要修改a中的变量,则需要在b中继续使用global

 

posted @ 2022-05-31 14:13  海_纳百川  阅读(32)  评论(0编辑  收藏  举报
本站总访问量