- 作用域
变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称,Python的作用域一共有4中
a、L(Local)局部作用域
b、E(Enclosing)闭包函数外的函数中
c、G(Global)全局作用域
e、B(Built-in)内建作用域
以 L--> E --> G --> B 的规则查找,即,在局部找不到,便回去局部外找(如闭包),再找不到就会去全局找,再者去内建中找
x = int(2.9) #内建作用域
g_count = 0 #全局作用域
def outer():
o_count = 1 #闭包函数外的函数中
def inner():
i_count = 2 #局部作用域
6
1
x = int(2.9) #内建作用域
2
g_count = 0 #全局作用域
3
def outer():
4
o_count = 1 #闭包函数外的函数中
5
def inner():
6
i_count = 2 #局部作用域
Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其他的代码块(如 if/elif/try/except/for/while等)都不会引入新的作用域,也就说这些语句内定义的变量,外部也可以访问
- 全局变量和局部变量
a、定义在函数内容的变量拥有一个局部作用域,定义在函数外的拥有全局的作用域
b、局部比那里只能在被声明的函数内部访问,而全局变量可以在整个程序范围内访问,调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。
total = 0 #全局变量
def sum(arg1,arg2):
total = arg1 + arg2 #total在这里是局部变量
print ("函数内的局部变量",total)
return total
sum(10,20)
print ("函数外是全局变量",total)
#输出
函数内是局部变量 : 30
函数外是全局变量 : 0
11
1
total = 0 #全局变量
2
def sum(arg1,arg2):
3
total = arg1 + arg2 #total在这里是局部变量
4
print ("函数内的局部变量",total)
5
return total
6
sum(10,20)
7
print ("函数外是全局变量",total)
8
9
#输出
10
函数内是局部变量 : 30
11
函数外是全局变量 : 0
- global 和 nonlocal 关键字
当内部作用域想修改外部作用域的变量时,就可用到 global 和 nonlocal 关键字
num = 1
def fun1():
global num #需要使用 global 关键字声明
print (num)
num = 123
print (num)
fun1()
#输出
1
123
11
1
num = 1
2
def fun1():
3
global num #需要使用 global 关键字声明
4
print (num)
5
num = 123
6
print (num)
7
fun1()
8
9
#输出
10
1
11
123
如果要修改嵌套作用域(enclosing 作用域 ,外层非全局作用域)中的变量则需要 nonlocal 关键字
def outer():
num = 10
def inner():
nonlocal num #nonlocal关键字声明
num =100
print(num)
inner()
print(num)
outer()
#输出
100
100
13
1
def outer():
2
num = 10
3
def inner():
4
nonlocal num #nonlocal关键字声明
5
num =100
6
print(num)
7
inner()
8
print(num)
9
outer()
10
11
#输出
12
100
13
100
错误的案例
a = 10
def test():
a = a + 1
print(a)
test()
#输出报错
# UnboundLocalError: local variable 'a' referenced before assignment
#错误信息为局部作用域引用错误,因为 test 函数中的 a 使用的是局部,未定义,无法修改
#想引用则 可用global 声明
a = 10
def test():
global a #使用global 声明
a = a + 1
print(a)
test()
17
1
a = 10
2
def test():
3
a = a + 1
4
print(a)
5
test()
6
7
#输出报错
8
# UnboundLocalError: local variable 'a' referenced before assignment
9
#错误信息为局部作用域引用错误,因为 test 函数中的 a 使用的是局部,未定义,无法修改
10
#想引用则 可用global 声明
11
a = 10
12
def test():
13
global a #使用global 声明
14
a = a + 1
15
print(a)
16
test()
17