脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python nonlocal关键字 与 global 关键字解析

Python nonlocal关键字 与 global 关键字解析

2022-11-13 10:09Brad1994 Python

这篇文章主要介绍了Python nonlocal关键字 与 global 关键字解析,nonlocal关键字用来在函数或其他作用域中使用外层变量,global关键字用来在函数或其他局部作用域中使用全局变量,更多香瓜内容需要的小伙伴可以参考一下

python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量

1.nonlocal

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

首先:要明确 nonlocal 关键字是定义在闭包里面的。

请看以下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
x = 0
def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)
 
    inner()
    print("outer:", x)
 
outer()
print("global:", x)

结果:

# inner: 2
# outer: 1
# global: 0

现在,在闭包里面加入nonlocal关键字进行声明:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:", x)
 
    inner()
    print("outer:", x)
 
outer()
print("global:", x)

结果:

# inner: 2
# outer: 2
# global: 0

看到区别了么?这是一个函数里面再嵌套了一个函数。当使用 nonlocal 时,就声明了该变量不只在嵌套函数inner()里面才有效, 而是在整个大函数里面都有效。

2.global

global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。

还是一样,看一个例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
x = 0
def outer():
    x = 1
    def inner():
        global x
        x = 2
        print("inner:", x)
 
    inner()
    print("outer:", x)
 
outer()
print("global:", x)

结果:

# inner: 2
# outer: 1
# global: 2

global 是对整个环境下的变量起作用,而不是对函数类的变量起作用。

到此这篇关于Python nonlocal关键字 与 global 关键字解析的文章就介绍到这了,更多相关nonlocal 与 global 关键字内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/brad1994/p/6533267.html

延伸 · 阅读

精彩推荐