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

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

    Other answers have demonstrated the way you should do this. Here's a way you shouldn't:

    >>> def foo(counter=[0]):
    ...   counter[0] += 1
    ...   print("Counter is %i." % counter[0]);
    ... 
    >>> foo()
    Counter is 1.
    >>> foo()
    Counter is 2.
    >>> 
    

    Default values are initialized only when the function is first evaluated, not each time it is executed, so you can use a list or any other mutable object to store static values.

提交回复
热议问题