Simulating a 'local static' variable in python

后端 未结 5 1205
盖世英雄少女心
盖世英雄少女心 2020-11-29 22:11

Consider the following code:

def CalcSomething(a):
    if CalcSomething._cache.has_key(a):
      return CalcSomething._cache[a]
    CalcSomething._cache[a]         


        
5条回答
  •  [愿得一人]
    2020-11-29 22:13

    Turn it into a callable object (since that's what it really is.)

    class CalcSomething(object):
        def __init__(self):
            self._cache = {}
        def __call__(self, a):
            if a not in self._cache: 
                self._cache[a] = self.reallyCalc(a)
            return self._cache[a]
        def reallyCalc(self, a):
            return # a real answer
    calcSomething = CalcSomething()
    

    Now you can use calcSomething as if it were a function. But it remains tidy and self-contained.

提交回复
热议问题