Closures in Python

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

    I think the best way would be:

    class Memoized(object):
        def __init__(self,func):
            self.cache = {}
            self.func = func
        def __call__(self,*args):
            if args in self.cache: return cache[args]
            else:
                self.cache[args] = self.func(*args)
                return self.cache[args]
    

提交回复
热议问题