考虑以下代码:
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", { } )
在函数的定义里面,这确实很麻烦。
有更优雅的方式吗?
[EDIT]
只是为了澄清,这个问题与本地函数缓存无关,如上面的示例所示。这是另一个简短的例子,其中“静态本地”可能很方便:
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
就好像它是一个函数一样。但它仍然整洁且独立。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)