Python inner functions

后端 未结 3 2016
忘了有多久
忘了有多久 2020-12-17 19:51

In python, I can write :

def func():
    x = 1
    print x
    x+=1

    def _func():
        print x
    return _func

test = func()
test()
3条回答
  •  -上瘾入骨i
    2020-12-17 20:32

    You can't rebind variables that are closed over in Python 2 (you can use nonlocal in Python 3). If I have to do what you're doing in Python 2 then I do the following workaround:

    class Pointer(object):
        def __init__(self, val):
            self.val = val
    
    def func():
        px = Pointer(1)
        print px.val
        px.val += 1
    
        def _func():
            print px.val
        return _func
    
    test = func()
    test()
    

    Basically I put whatever values I need to be mutated onto an object - sometimes I use a list with one element - and then re-write the code so that all that happens is method calls. The above is actually equivalent to:

    class Pointer(object):
        def __init__(self, val):
            self.val = val
    
    def func():
        px = Pointer(1)
        print px.val
        px.__setattr__('val', px.val + 1)
    
        def _func():
            print px.val
        return _func
    
    test = func()
    test()
    

提交回复
热议问题