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

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

    A little bit more readable, but more verbose (Zen of Python: explicit is better than implicit):

    >>> def func(_static={'counter': 0}):
    ...     _static['counter'] += 1
    ...     print _static['counter']
    ...
    >>> func()
    1
    >>> func()
    2
    >>>
    

    See here for an explanation of how this works.

提交回复
热议问题