目录
变量作用域与命名空间
Python变量的作用域
变量的作用域就是变量有效(能访问)的代码区域(代码块范围)。
变量的有效代码区域基本上按照下面规律。
- 变量能在所在代码块内以及子代码内有效;
- 当代码区域与子代码区定义的变量重名时,子代码区中的变量有效范围是子代码区内,外层变量有效范围是外层及其他不重名变量的子代码区。
代码块内可以直接使用代码块外的变量。
a=123
def myfun():
print("myfun:",a)
myfun()
print("outer:",a)
程序运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
myfun: 123
outer: 123
Process finished with exit code 0
但是,如果代码块内定义的变量与外面的变量同名时,代码块内使用的是块内变量,外层依然是外层变量。
a=123
def myfun():
a=5
print("myfun:",a)
myfun()
print("outer:",a)
程序运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
myfun: 5
outer: 123
Process finished with exit code 0
全局变量与局部变量
全局变量是指作用域是最外层代码块中的变量,比如.py文件。
局部变量指变量作用域是内层代码块,比如函数块内。
对于不可变类型变量,如果想在内层代码块中修改外层全局变量,可以使用global关键字(先声明,再使用)。
a=123
def myfun():
global a
a=5
print("myfun:",a)
myfun()
print("outer:",a)
程序运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
myfun: 5
outer: 5
Process finished with exit code 0
对于可变类型变量,可以直接在内层代码块中修改外层变量的值,不需要使用global关键字声明。
a=[123]
def myfun():
a[0]=5
print("myfun:",a)
myfun()
print("outer:",a)
程序运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
myfun: [5]
outer: [5]
Process finished with exit code 0
Python变量的命名空间
命名空间又叫名称空间,可以用来区分变量的作用域,防止变量命名冲突。相同的变量名可以定义在不同的命名空间中,他们名称相同,但是被划分到不同的空间中,是互不相关的变量。
命名空间对变量的管理,相当于文件夹对文件的管理。同一个文件夹中不允许有重名文件,但是不同文件夹内可以放文件名称相同的文件。
Java语言中用包作为命名空间,Python中用模块作为命名空间(模块在以后讲解)。