在python中模拟“局部静态"变量 [英] Simulating a 'local static' variable in python

查看:43
本文介绍了在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 在函数定义之外被提及,但替代方案是这样的:

This is the easiest way I can think of for simulating a 'local static' variable in python.
What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that:

if not hasattr(CalcSomething, "_cache"):  
    setattr(CalcSomething, "_cache", { } )  

在函数的定义里面,真的很麻烦.

inside the function's definition, which is really cumbersome.

有没有更优雅的方式?


只是为了澄清,这个问题与本地函数缓存无关,如上面的示例所示.这是另一个简短的示例,其中静态本地"可能很方便:


Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy:

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() 

推荐答案

把它变成一个可调用的对象(因为它确实是这样.)

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()

现在您可以像使用函数一样使用 calcSomething.但它仍然保持整洁和独立.

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

这篇关于在python中模拟“局部静态"变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆