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

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

    The idiomatic way is to use a class, which can have attributes. If you need instances to not be separate, use a singleton.

    There are a number of ways you could fake or munge "static" variables into Python (one not mentioned so far is to have a mutable default argument), but this is not the Pythonic, idiomatic way to do it. Just use a class.

    Or possibly a generator, if your usage pattern fits.

提交回复
热议问题