What is the Python equivalent of static variables inside a function?

前端 未结 26 2733
天命终不由人
天命终不由人 2020-11-22 00:45

What is the idiomatic Python equivalent of this C/C++ code?

void foo()
{
    static int counter = 0;
    counter++;
          


        
26条回答
  •  甜味超标
    2020-11-22 01:34

    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.

提交回复
热议问题