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

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

    I write a simple function to use static variables:

    def Static():
        ### get the func object by which Static() is called.
        from inspect import currentframe, getframeinfo
        caller = currentframe().f_back
        func_name = getframeinfo(caller)[2]
        # print(func_name)
        caller = caller.f_back
        func = caller.f_locals.get(
            func_name, caller.f_globals.get(
                func_name
            )
        )
        
        class StaticVars:
            def has(self, varName):
                return hasattr(self, varName)
            def declare(self, varName, value):
                if not self.has(varName):
                    setattr(self, varName, value)
    
        if hasattr(func, "staticVars"):
            return func.staticVars
        else:
            # add an attribute to func
            func.staticVars = StaticVars()
            return func.staticVars
    

    How to use:

    def myfunc(arg):
        if Static().has('test1'):
            Static().test += 1
        else:
            Static().test = 1
        print(Static().test)
    
        # declare() only takes effect in the first time for each static variable.
        Static().declare('test2', 1)
        print(Static().test2)
        Static().test2 += 1
    

提交回复
热议问题