函数内静态变量的 Python 等价物是什么?

新手上路,请多包涵

此 C/C++ 代码的惯用 Python 等价物是什么?

 void foo()
{
    static int counter = 0;
    counter++;
    printf("counter is %d\n", counter);
}

具体来说,如何在函数级别而不是类级别实现静态成员?将函数放入类中会改变什么吗?

原文由 andrewdotnich 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 414
2 个回答

有点颠倒,但这应该有效:

 def foo():
    foo.counter += 1
    print "Counter is %d" % foo.counter
foo.counter = 0

如果你想在顶部而不是底部的计数器初始化代码,你可以创建一个装饰器:

 def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            setattr(func, k, kwargs[k])
        return func
    return decorate

然后使用这样的代码:

 @static_vars(counter=0)
def foo():
    foo.counter += 1
    print "Counter is %d" % foo.counter

不幸的是,它仍然需要您使用 foo. 前缀。

(来源: @ony

原文由 Claudiu 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以向函数添加属性,并将其用作静态变量。

 def myfunc():
  myfunc.counter += 1
  print myfunc.counter

# attribute must be initialized
myfunc.counter = 0

或者,如果您不想在函数外设置变量,您可以使用 hasattr() 来避免 AttributeError 异常:

 def myfunc():
  if not hasattr(myfunc, "counter"):
     myfunc.counter = 0  # it doesn't exist yet, so initialize it
  myfunc.counter += 1

不管怎样,静态变量很少见,你应该为这个变量找到一个更好的地方,很可能是在一个类中。

原文由 vincent 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题