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

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

    Other solutions attach a counter attribute to the function, usually with convoluted logic to handle the initialization. This is inappropriate for new code.

    In Python 3, the right way is to use a nonlocal statement:

    counter = 0
    def foo():
        nonlocal counter
        counter += 1
        print(f'counter is {counter}')
    

    See PEP 3104 for the specification of the nonlocal statement.

    If the counter is intended to be private to the module, it should be named _counter instead.

提交回复
热议问题