如何在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        

猜你喜欢

转载自www.cnblogs.com/chaoguo1234/p/9218299.html