Python函数(六)-嵌套函数

嵌套函数就是在一个函数里再嵌套一个或多个函数

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

def First():
    print("in the first")
    def Second():
        print("in the second")
        def Third():
            print("in the third")
        Third()
    Second()
First()

运行结果

如果要修改嵌套作用域中的变量,则需要nonlocal关键字

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
 
def outer():
    name = 'John'
    def inner():
        nonlocal name
        name = 'Jack'
        print(name)
    inner()
    print(name)
outer()

运行结果

 

posted @ 2018-02-01 19:15  Sch01aR#  阅读(466)  评论(0编辑  收藏  举报