一个例子说明nonlocal

global 很显然是解决variable的全局变量问题

 

而nonlocal是为了解决     嵌套函数中

 

变量的修改问题

 

这样是会报错的:

def tester(start):
    state=start
    def nested(label):
        print(label,state)
        state+=1
    return nested

F=tester(0)
F("spam")
F("ham")
F("egg")

 

加上nonlocal才是正确的:

def tester(start):
    state=start
    def nested(label):
        nonlocal state
        print(label,state)
        state+=1
    return nested

F=tester(0)
F("spam")
F("ham")
F("egg")

 

注意state=start是必不可少的,在内部嵌套函数之外这个变量必须要首先已经被声明过了 

 

posted @ 2021-08-27 23:02  TheDa  阅读(47)  评论(0编辑  收藏  举报