变量的做用域决定了在哪一部分程序能够访问哪一个特定的变量名称,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 #局部做用域
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
当内部做用域想修改外部做用域的变量时,就可用到 global 和 nonlocal 关键字
num = 1
def fun1():
global num #须要使用 global 关键字声明
print (num)
num = 123
print (num)
fun1()
#输出
1
123
若是要修改嵌套做用域(enclosing 做用域 ,外层非全局做用域)中的变量则须要 nonlocal 关键字
def outer():
num = 10
def inner():
nonlocal num #nonlocal关键字声明
num =100
print(num)
inner()
print(num)
outer()
#输出
100
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()