自学Python--函数嵌套和作用域链

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41402059/article/details/82287568

函数的嵌套定义:

def outer():
    print('outer')
    def inner():
        print('inner')

outer() # outer

global只声明全局变量,不管函数嵌套多少层,如果想改变最近一层局部变量,使用nonlocal,如果找不到上层局部变量会报错

a = 1
def outer():
    a = 2
    def inner():
        global a
        a += 1
    inner()
outer()
print(a) # 2
a = 1
def outer():
    a = 2
    def inner():
        nonlocal a
        a += 1
    inner()
    print('outer->a',a)
outer() # outer->a 3

函数名可以赋值给变量,也可以作为另一个函数的入参,也可以作为函数返回值(一切皆对象)

猜你喜欢

转载自blog.csdn.net/weixin_41402059/article/details/82287568