Closures in Python

后端 未结 6 1973
南旧
南旧 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:23

    Probably because you want the global get while it isn't a global? By the way, apply is deprecated, use fn(*args) instead.

    def memoize(fn):
        def get(key):
            return (False,)
    
        def vset(key, value):
            def newget(ky):
                if key==ky: return (True, value)
                return get(ky)
            get = newget
    
        def mfun(*args):
            cache = get(args)
            if (cache[0]): return cache[1]
    
            val = fn(*args)
            vset(args, val)
            return val
    
        return mfun
    
    def fib(x):
        if x<2: return x
        return fib(x-1)+fib(x-2)
    
    def fibm(x):
        if x<2: return x
        return fibm(x-1)+fibm(x-2)
    
    fibm = memoize(fibm)
    

提交回复
热议问题