Closures in Python

后端 未结 6 1983
南旧
南旧 2020-12-17 00:42

I\'ve been trying to learn Python, and while I\'m enthusiastic about using closures in Python, I\'ve been having trouble getting some code to work properly:

         


        
6条回答
  •  被撕碎了的回忆
    2020-12-17 01:17

    Get is not global, but local to the surrounding function, that's why the global declaration fails.

    If you remove the global, it still fails, because you can't assign to the captured variable name. To work around that, you can use an object as the variable captured by your closures and than just change properties of that object:

    class Memo(object):
        pass
    
    def memoize(fn):
        def defaultget(key):
            return (False,)
    
        memo = Memo()
        memo.get = defaultget
    
        def vset(key, value):
            oldget = memo.get
            def newget(ky):
                if key==ky: return (True, value)
                return oldget(ky)
            memo.get = newget
    
        def mfun(*args):
            cache = memo.get(args)
            if cache[0]: return cache[1]
    
            val = apply(fn, args)
            vset(args, val)
            return val
    
        return mfun
    

    This way you don't need to assign to the captured variable names but still get what you wanted.

提交回复
热议问题