What is the lifetime of a variable in the method, in the class, and in the module?

1

I know that a variable declared in a method lasts for the duration of the method scope. As python has the concept of class variables, how long does a variable declared in the class last? Is a variable declared loose in a module, when it "is born" and when it "dies"?

    
asked by anonymous 07.02.2016 / 16:11

1 answer

0

The variable will exist as long as there is a reference to it. As soon as the reference counter reaches 0, the variable is cleared. This is independent of where the reference resides inside or outside a class.

Variables declared in modules are created at the time the code that defines them is executed. This usually occurs at the time the module is imported, unless some condition within the module prevents it.

A fairly common "idiom" in Python is this:

# várias definições
# ........

if __name__ == "__main__":
    # executar algum código
    # .....

# fim do arquivo

If you set a variable within this if , it will only be created if that module runs directly instead of imported. The names defined above if are initialized both when the module is imported and when it is run directly. Of course the same is true if there is no such thing as if .

Global variables for the module generally exist forever, since imported modules have references to them in sys.modules . This reference prevents garbage collection, so unless your module is removed directly from it (using del ), variables defined in the module will continue to exist.

    
07.02.2016 / 21:36