python3的嵌套函数

背景

最近在学python3

嵌套函数

顾名思义,即使在函数中还有函数,实现了函数的多级嵌套

def test1():
    age = 10

    print(age)

    def test2():
        te = 5
        print(age)

        def test3():
            print(te)
        test3()

test1()
    

输出结果:

10

test2()方法没有被执行,这是因为任意函数在定义完成之后,需要通过函数名来进行引用调用,如果没有调用,那么该函数永远不会执行。

def test1():
    age = 10

    print(age)

    def test2():
        te = 5
        print(age)

        def test3():
            print(te)
        
        test3()
    test2()

test1()
    

输出结果:

10
10
5

还拿上面的例子进行学习。在嵌套函数内部,函数引用变量的时候是一层一层的向外找,同时需要注意代码的上下顺序,被调用的变量不能在调用函数的下方定义

age = 18
 
def func1():
    # age = 20   放在上面
 
    def func2():
        print(age)
 
    age = 20    #放在下面,其实都是放在func2的上面
    func2()
 
func1()

输出结果:

Traceback (most recent call last):
  File "嵌套函数.py", line 13, in <module>
    func1()
  File "嵌套函数.py", line 10, in func1
    func2()
  File "嵌套函数.py", line 8, in func2
    print(age)
NameError: free variable 'age' referenced before assignment in enclosing scope
原文地址:https://www.cnblogs.com/lishanlei/p/10707859.html