首页 > 其他 > 详细

一个例子说明nonlocal

时间:2021-08-30 08:08:25      阅读:19      评论:0      收藏:0      [点我收藏+]

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是必不可少的,在内部嵌套函数之外这个变量必须要首先已经被声明过了 

 

一个例子说明nonlocal

原文:https://www.cnblogs.com/theda/p/15195555.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!