函数内静态变量的 Python 等价物是什么? [英] What is the Python equivalent of static variables inside a function?
本文介绍了函数内静态变量的 Python 等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个 C/C++ 代码的惯用 Python 等价物是什么?
What is the idiomatic Python equivalent of this C/C++ code?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
具体来说,相对于类级别,如何在函数级别实现静态成员?将函数放入一个类中会改变什么吗?
specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
推荐答案
有点颠倒,但这应该有效:
A bit reversed, but this should work:
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
foo.counter = 0
如果你想要计数器初始化代码在顶部而不是底部,你可以创建一个装饰器:
If you want the counter initialization code at the top instead of the bottom, you can create a decorator:
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.
前缀.
It'll still require you to use the foo.
prefix, unfortunately.
(来源:@ony)
这篇关于函数内静态变量的 Python 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文