Python 函数的作用域

Python中的作用域有4种:

名称 介绍
L local,局部作用域,函数中定义的变量;
E enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是全局的;
B globa,全局变量,就是模块级别定义的变量;
G built-in,系统固定模块里面的变量,比如int, bytearray等。

搜索变量的优先级顺序依次是(LEGB):
作用域局部 > 外层作用域 > 当前模块中的全局 > python内置作用域。

number = 10            # number 是全局变量,作用域在整个程序中
def test():
    print(number)
    a = 8              # a 是局部变量,作用域在 test 函数内
    print(a)

test()

运行结果:

10
8
def outer():
    o_num = 1          # enclosing
    i_num = 2          # enclosing
    def inner():
        i_num = 8      # local
        print(i_num)  # local 变量优先
        print(o_num)
    inner()
outer()

运行结果:
8
1
num = 1
def add():
    num += 1
    print(num)
add()

运行结果:
UnboundLocalError: local variable 'num' referenced before assignment

如果想在函数中修改全局变量,需要在函数内部在变量前加上 global 关键字
num = 1                    # global 变量
def add():
    global num            # 加上 global 关键字
    num += 1
    print(num)
add()

运行结果:
2

同理,如果希望在内层函数中修改外层的 enclosing 变量,需要加上 nonlocal 关键字
def outer():
    num = 1                  # enclosing 变量
    def inner():
        nonlocal num        # 加上 nonlocal 关键字
        num = 2
        print(num)
    inner()
    print(num)
outer()

运行结果:
2
2

另外我们需要注意的是:

1.只有模块、类、及函数才能引入新作用域;
2.对于一个变量,内部作用域先声明就会覆盖外部变量,不声明直接使用,就会使用外部作用域的变量(这时只能查看,无法修改);
3.如果内部作用域要修改外部作用域变量的值时, 全局变量要使用 global 关键字,嵌套作用域变量要使用 nonlocal 关键字。

猜你喜欢

转载自www.linuxidc.com/Linux/2018-04/151750.htm