如何在Python 2.X中也达到类似nonlocal关键字的效果

nonlocal关键字时Python 3.X中引入的,目的是让内层函数可以修改外层函数的变量值,而该关键字在Python 2.X中是不存在的。那么,要在Python 2.X中达到类型达到类似nonlocal关键字的效果,有方法吗?

 

答案是肯定的,主要有如下四种方法:

1 将要改变的变量在外层函数声明成global的,这样内层函数就可以改变这个变量的值了,缺点就是所有内层函数都共享一个全局变量的值:

复制代码
def test(start):
    global state    # 将state声明成全局变量
    state = start

    def nested(label):
        global state           # 必须使用global再次声明,否则state += 1会报错,因此不使用global声明,Python认为state是在nested里面声明的一个局部变量,而这个变量没有被定义(即没有被赋值),就被拿来使用了
        print(label, state)
        state += 1
    
    return nested


>>>F = test(1)
>>>F('toast')
toast  1

>>> G = test(42)
>>>G('spam')
spam 42

>>>F('ham')    # F和G都共享一个全局变量state,导致F的state变成了43
ham 43
复制代码

2 使用class

复制代码
class tester:
    def __init__(self, start): 
        self.state = start        
    def nested(self, label):
        print(label, self.state)  
        self.state += 1         


>>>F = test(0)
>>>F.nested('spam')
spam 0      
复制代码

3 使用函数的属性,由于函数在Python里面是一个对象,因此可以给它添加属性,我们可以利用这一点达到目的

def tester(start):
    def nested(label):
        print(label, nested.state)  
        nested.state += 1  
    nested.state = start     # state作为函数属性
    return nested                

4 利用可变的数据结构,比如数组,但是相比较使用class和函数的属性,这种使用方式很晦涩

def tester(start):
    def nested(label):
        print(label, state[0])  
        state[0] += 1 
    state = [start]   # 通过数组达到这一目的
    return nested        

 

posted @   chaoguo1234  阅读(1297)  评论(1编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2013-06-23 从汇编看c++中指向成员变量的指针(一)
点击右上角即可分享
微信分享提示