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

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

    A global declaration provides this functionality. In the example below (python 3.5 or greater to use the "f"), the counter variable is defined outside of the function. Defining it as global in the function signifies that the "global" version outside of the function should be made available to the function. So each time the function runs, it modifies the value outside the function, preserving it beyond the function.

    counter = 0
    
    def foo():
        global counter
        counter += 1
        print("counter is {}".format(counter))
    
    foo() #output: "counter is 1"
    foo() #output: "counter is 2"
    foo() #output: "counter is 3"
    

提交回复
热议问题