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

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

    def staticvariables(**variables):
        def decorate(function):
            for variable in variables:
                setattr(function, variable, variables[variable])
            return function
        return decorate
    
    @staticvariables(counter=0, bar=1)
    def foo():
        print(foo.counter)
        print(foo.bar)
    

    Much like vincent's code above, this would be used as a function decorator and static variables must be accessed with the function name as a prefix. The advantage of this code (although admittedly anyone might be smart enough to figure it out) is that you can have multiple static variables and initialise them in a more conventional manner.

提交回复
热议问题