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

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

    Using an attribute of a function as static variable has some potential drawbacks:

    • Every time you want to access the variable, you have to write out the full name of the function.
    • Outside code can access the variable easily and mess with the value.

    Idiomatic python for the second issue would probably be naming the variable with a leading underscore to signal that it is not meant to be accessed, while keeping it accessible after the fact.

    An alternative would be a pattern using lexical closures, which are supported with the nonlocal keyword in python 3.

    def make_counter():
        i = 0
        def counter():
            nonlocal i
            i = i + 1
            return i
        return counter
    counter = make_counter()
    

    Sadly I know no way to encapsulate this solution into a decorator.

提交回复
热议问题