Static class members python

Falmarri picture Falmarri · Aug 17, 2010 · Viewed 12.3k times · Source

So I'm using static class members so I can share data between class methods and static methods of the same class (there will only be 1 instantiation of the class). I understand this fine, but I'm just wondering when the static members get initialized? Is it on import? On the first use of the class? Because I'm going to be calling the static members of this class from more than 1 module (therefore more than 1 import statement). Will all the modules accessing the static methods share the same static data members? And if my main client deletes the instance of my class, and then recreates it (without terminating altogether or re-importing stuff), will my data members be preserved?

Answer

Triptych picture Triptych · Aug 17, 2010

They will be initialized at class definition time, which will happen at import time if you are importing the class as part of a module. This assuming a "static" class member definition style like this:

class Foo:
    bar = 1

print Foo.bar # prints '1'

Note that, this being a static class member, there is no need to instantiate the class.

The import statement will execute the contents of a module exactly once, no matter how many times or where it is executed.

Yes, the static members will be shared by any code accessing them.

Yes, the static members of a class will be preserved if you delete an object whose type is that class:

# Create static member
class Foo:
    bar = 1

# Create and destroy object of type Foo
foo = Foo()
del foo

# Check that static members survive
print Foo.bar # Still prints '1'