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

前端 未结 26 2735
天命终不由人
天命终不由人 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:33

    _counter = 0
    def foo():
       global _counter
       _counter += 1
       print 'counter is', _counter
    

    Python customarily uses underscores to indicate private variables. The only reason in C to declare the static variable inside the function is to hide it outside the function, which is not really idiomatic Python.

提交回复
热议问题