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

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

    Many people have already suggested testing 'hasattr', but there's a simpler answer:

    def func():
        func.counter = getattr(func, 'counter', 0) + 1
    

    No try/except, no testing hasattr, just getattr with a default.

提交回复
热议问题