变量,是在内存中开辟一块内存来存储数据。每个变量都有自己的作用域和生命周期。熟知不同变量的作用域和生命周期,在开发中是十分必要和基础的。不同的开发语言变量有它自己的特点,要注意不同之处。
Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的。
变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。Python的作用域一共有4种,分别是:
L (Local) 局部作用域
E (Enclosing) 闭包函数外的函数中
G (Global) 全局作用域
B (Built-in) 内建作用域
以 L –> E –> G –>B 的规则查找,即:在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内建中找。
Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的,也就是说这些语句内定义的变量,外部也可以访问。而在C\java\Objective-C\swift中,代码块内同样会产生新的作用域。
例如:
if True:
msg = "True"
print('msg =', msg)
运行结果:
msg = True
函数内则是会产生新的作用域的,例如:
# 变量作用域
def get_sum(n1, n2):
print('函数内:n1 =', n1)
return n1 + n2
# 调用函数
print(get_sum(3, 4))
运行结果:
函数内:n1 = 3
7
倘若,在函数外也访问n1,则就超出了n1的作用域,则会提示:NameError: name 'n1' is not defined
# 变量作用域
def get_sum(n1, n2):
print('函数内:n1 =', n1)
return n1 + n2
# 调用函数
print(get_sum(3, 4))
print('函数外:n1', n1)
运行结果:
Traceback (most recent call last):
File "F:/python_projects/11var_field.py", line 10, in <module>
print('函数外:n1', n1)
NameError: name 'n1' is not defined
函数内:n1 = 3
7
报错:NameError: name 'n1' is not defined。即:名字错误:变量n1未定义。这是因为它是局部变量,只有在函数内可以使用。
全局变量和局部变量
定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。
局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。
# 全局变量
total = 0
# 变量作用域
def get_sum(n1, n2):
print('函数内:n1 =', n1)
# 局部变量total
total = n1 + n2
print('函数内:total =', total)
return total
# 调用函数
print(get_sum(3, 4))
print('函数外:total =', total)
运行结果:
函数内:n1 = 3
函数内:total = 7
7
函数外:total = 0
在函数内部,修改局部变量total,默认情况下是不会影响函数外部的同名变量的。当内部作用域想要修改外部作用域的变量时,就要用到global和nonlocal关键字了。
global和nonlocal关键字
当内部作用域想修改外部作用域的变量时,就要用到global
和nonlocal
关键字了。
# 全局变量
total = 0
# 变量作用域
def get_sum(n1, n2):
# 使用global 修饰total后,局部修改total的值,外面的total的值也同时改变
global total
print('函数内:n1 =', n1)
total = n1 + n2
print('函数内:total =', total)
return total
# 调用函数
print(get_sum(3, 4))
print('函数外:total =', total)
运行结果:
函数内:n1 = 3
函数内:total = 7
7
函数外:total = 7
函数内部,使用global 修饰total后,局部修改total的值,外面的total的值也同时改变。所以函数外部的total的值,也变成了7。
如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字了,如下实例:
def outer():
num = 10
# 定义内部
def inner():
nonlocal num # nonlocal关键字声明
num = 100
print(num)
inner()
print(num)
# 调用函数
outer()
运行结果:
100
100
小结:
本文学习了Python中变量的作用域,这个知识将贯穿以后的整个开发过程,必须是否清楚这个知识。
更多了解,可关注公众号:人人懂编程

网友评论