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

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

    Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function. Also see this answer.

    class Foo(object):
      # Class variable, shared by all instances of this class
      counter = 0
    
      def __call__(self):
        Foo.counter += 1
        print Foo.counter
    
    # Create an object instance of class "Foo," called "foo"
    foo = Foo()
    
    # Make calls to the "__call__" method, via the object's name itself
    foo() #prints 1
    foo() #prints 2
    foo() #prints 3
    

    Note that __call__ makes an instance of a class (object) callable by its own name. That's why calling foo() above calls the class' __call__ method. From the documentation:

    Instances of arbitrary classes can be made callable by defining a __call__() method in their class.

提交回复
热议问题