Python 中的变量作用域

2024 年 8 月 29 日 | 阅读 6 分钟

Python 语言中的变量充当各种数据值和数据结构的存储单元。当一个变量被赋值给任何 Python 对象时,它会指向该对象,因为它们是指向内存位置中特定对象的引用或指针。Python 编程语言不像 C/C++/JAVA 等其他语言那样是“静态类型的”。在显式声明变量的类型或初始值之前,不需要声明。当变量被赋予初始值时,即认为它已被创建。

代码

输出

This value is stored in the variable 'integer':-  45
This value is stored in the variable 'floating':-  1456.8
This value is stored in the variable 'string':-  John

变量作用域

Python 变量的作用域是指我们可以找到它,并在必要时访问它的区域。

全局变量和局部变量

全局变量是在任何函数外部声明和定义的变量,不特定于任何函数。程序的任何部分都可以使用它们。

代码

输出

This is in the main function:- 
2
This is in function 'f1()':- 
2
This is in function 'f2()':- 
2

假设一个变量在函数的局部作用域内定义,并且它与全局变量具有相同的名称。在这种情况下,它将仅显示在该特定函数内为变量提供的值,而不是全局作用域中赋给它的值。

代码

输出

This is defined inside the function.

在定义函数 func() 之前,变量 'a' 被赋值为字符串“This is assigned in the global scope.”。函数 func() 的 print(a) 语句将首先在其局部作用域中搜索变量 'a'。由于已经有一个变量 'a' 被赋值为不同的字符串,该函数将打印该变量的值,而不会查找全局作用域。在这种情况下,函数将不会使用全局作用域中的变量 'a' 的值。

下一个问题是,在函数 'func()' 中修改变量 'a' 的值会有什么结果?这是否也会影响全局变量 'a'?下面的代码片段用于测试这一点

代码

输出

Accessed in the local scope of function:-  This is defined inside the function.
Accessed in the global scope:-  This is assigned in the global scope.

我们必须使用 Python 的 global 关键字才能使前面的程序起作用。只有在赋值或更改变量值时,我们才需要在函数内部使用 Python 的 global 关键字。显示和访问全局作用域中存在的变量不需要 global 关键字。为什么?由于在 func() 内部对变量 'a' 进行了赋值,Python“假定”我们想要访问局部变量,这就是为什么第一个 print 命令返回局部作用域中变量值的原因。如果在函数内部修改或赋值了一个变量,而没有将其定义为全局变量,那么它将被视为局部变量。下面的示例演示了如何使用 global 关键字指示 Python 解释器我们希望修改全局变量

代码

输出

Accessed in the local scope of function:-  This is defined inside the function.
Accessed in the global scope:-  This is defined inside the function.

总结全局局部变量作用域。

代码

输出

global:  in the global scope
Inside func():  in the global scope
global:  in the global scope
Inside local(): 
inside function local()
global:  in the global scope
Inside global_() : 
changed inside function global_()
global:  changed inside function global_()

Nonlocal 关键字

在 Python 中,嵌套函数使用 Python 的 nonlocal 关键字进行处理。这个关键字的作用类似于 global 关键字,不同之处在于,在嵌套函数的情况下,它定义了一个变量来引用在外部封闭函数中赋给的变量,而不是全局变量。

代码

输出

Using the nonlocal keyword before changing a:
Inside 'inner' function:- 
14
Inside the 'outer' function:-  14
In the global scope:- 
0

Not using the nonlocal keyword before changing a:
Inside 'inner' function:- 
14
Inside the 'outer' function:-  3
In the global scope:- 
0