python - 在python中模拟一个 'local static'变量

标签 python

考虑以下代码:

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/

相关文章:

python - 如何修复 '' 发现输入变量的样本数量不一致 : [219, 247 ]''

Python:numpy 数组列表,不能做 index()?

python - 在pygame中添加/创建下拉选择框的技巧

python - 如何在 GPU 上有效并行化 AlphaZero?

python - Flask 应用程序在确认 Flask 安装后,elasticbeanstalk 中没有名为 Flask 的模块错误

python - bash 变量中的中文字符处理方式与文件中不同

用于带有磁盘空间的电子邮件警报的 Python 脚本

python - pytesseract OCR python 错误-示例代码

python - 如何在Python中处理API响应

python - PyMySQL 是否支持准备好的语句?