global和nonlocal的用法

1 nonlocal声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量.写在内部嵌套函数里面,它实质上是将该变量定义成了全局变量,它等价于用两个global来定义该变量.只不过用两个global来实现太繁琐.只用一个global的话无法在这儿(嵌套函数中)实现.

def make_counter():
    global count
    count = 0
    def counter():
        # nonlocal count
        global count
        count += 1
        return count
    return counter
mc = make_counter()
print(mc())
print(mc())
print(mc())
# 1
# 2
# 3
View Code

2 利用global可将函数的局部变量变为全局变量

# 全局变量在函数内部可以任意调用
hehe=6
def f():
    print(hehe)
f()
print(hehe)
# 6
# 6

# 注意这里在函数先输出hehe变量时,即先使用了它,后定义它是2,所以程序认为它是局部变量,会报先使用后定义的错误
hehe=6
def f():
    print(hehe)
    hehe=2
f()
print(hehe)
# UnboundLocalError: local variable 'hehe' referenced before assignment

# 这个是先定义后使用,函数内的hehe同样是局部变量
hehe=6
def f():
    hehe=2
    print(hehe)
f()
print(hehe)
# 2
# 6

hehe=6
def f():
    global hehe
    print(hehe)
    hehe=3
f()
print(hehe)
# 6
# 3
参考: https://www.cnblogs.com/summer-cool/p/3884595.html
View Code

https://www.cnblogs.com/yuzhanhong/p/9183161.html

https://www.liaoxuefeng.com/wiki/1016959663602400/1017434209254976#0

https://www.cnblogs.com/tallme/p/11300822.html

原文地址:https://www.cnblogs.com/xxswkl/p/12031721.html