考虑以下代码:
def CalcSomething(a):
if CalcSomething._cache.has_key(a):
return CalcSomething._cache[a]
CalcSomething._cache[a] = ReallyCalc(a)
return CalcSomething._cache[a]
CalcSomething._cache = { }
这是我能想到的在 python 中模拟“局部静态”变量的最简单方法。
困扰我的是 CalcSomething._cache 在函数定义之外被提及,但替代方案是这样的:
if not hasattr(CalcSomething, "_cache"):
setattr(CalcSomething, "_cache", { } )
在函数的定义里面,真的很麻烦。
有没有更优雅的方式?
[编辑]
澄清一下,这个问题与本地函数缓存无关,正如上面的示例所暗示的那样。下面是另一个“静态本地”可能很方便的简短示例:
def ParseString(s):
return ParseString._parser.parse(s)
# Create a Parser object once, which will be used for all parsings.
# Assuming a Parser object is heave on resources, for the sake of this example.
ParseString._parser = Parser()
最佳答案
把它变成一个可调用的对象(因为它是真的。)
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()
现在您可以像使用函数一样使用 calcSomething
。但它仍然保持整洁和独立。
关于python - 在python中模拟一个 'local static'变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/460586/