Python 函数的作用域

Linux大全评论1.2K views阅读模式

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

另外我们需要注意的是:

企鹅博客
  • 本文由 发表于 2019年7月28日 06:44:34
  • 转载请务必保留本文链接:https://www.qieseo.com/136495.html

发表评论