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

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

    Building on Daniel's answer (additions):

    class Foo(object): 
        counter = 0  
    
    def __call__(self, inc_value=0):
        Foo.counter += inc_value
        return Foo.counter
    
    foo = Foo()
    
    def use_foo(x,y):
        if(x==5):
            foo(2)
        elif(y==7):
            foo(3)
        if(foo() == 10):
            print("yello")
    
    
    use_foo(5,1)
    use_foo(5,1)
    use_foo(1,7)
    use_foo(1,7)
    use_foo(1,1)
    

    The reason why I wanted to add this part is , static variables are used not only for incrementing by some value, but also check if the static var is equal to some value, as a real life example.

    The static variable is still protected and used only within the scope of the function use_foo()

    In this example, call to foo() functions exactly as(with respect to the corresponding c++ equivalent) :

    stat_c +=9; // in c++
    foo(9)  #python equiv
    
    if(stat_c==10){ //do something}  // c++
    
    if(foo() == 10):      # python equiv
      #add code here      # python equiv       
    
    Output :
    yello
    yello
    

    if class Foo is defined restrictively as a singleton class, that would be ideal. This would make it more pythonic.

提交回复
热议问题