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

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

    A static variable inside a Python method

    class Count:
        def foo(self):
            try: 
                self.foo.__func__.counter += 1
            except AttributeError: 
                self.foo.__func__.counter = 1
    
            print self.foo.__func__.counter
    
    m = Count()
    m.foo()       # 1
    m.foo()       # 2
    m.foo()       # 3
    

提交回复
热议问题