What is the Python equivalent of static variables

2018-12-31 07:38发布

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?

标签: python
26条回答
几人难应
2楼-- · 2018-12-31 08:45

Use a generator function to generate an iterator.

def foo_gen():
    n = 0
    while True:
        n+=1
        yield n

Then use it like

foo = foo_gen().next
for i in range(0,10):
    print foo()

If you want an upper limit:

def foo_gen(limit=100000):
    n = 0
    while n < limit:
       n+=1
       yield n

If the iterator terminates (like the example above), you can also loop over it directly, like

for i in foo_gen(20):
    print i

Of course, in these simple cases it's better to use xrange :)

Here is the documentation on the yield statement.

查看更多
与风俱净
3楼-- · 2018-12-31 08:45

The idiomatic way is to use a class, which can have attributes. If you need instances to not be separate, use a singleton.

There are a number of ways you could fake or munge "static" variables into Python (one not mentioned so far is to have a mutable default argument), but this is not the Pythonic, idiomatic way to do it. Just use a class.

Or possibly a generator, if your usage pattern fits.

查看更多
登录 后发表回答