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

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

    You can add attributes to a function, and use it as a static variable.

    def myfunc():
      myfunc.counter += 1
      print myfunc.counter
    
    # attribute must be initialized
    myfunc.counter = 0
    

    Alternatively, if you don't want to setup the variable outside the function, you can use hasattr() to avoid an AttributeError exception:

    def myfunc():
      if not hasattr(myfunc, "counter"):
         myfunc.counter = 0  # it doesn't exist yet, so initialize it
      myfunc.counter += 1
    

    Anyway static variables are rather rare, and you should find a better place for this variable, most likely inside a class.

提交回复
热议问题