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?
+4
A:
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'
Triptych
2010-08-17 19:31:49
Yeah I realize I don't have to instantiate the class. But the class instance needs access to these members as well as other modules. My concerns it that I'm importing this module from several other modules. Will that mean the static members are reset for all modules? Or each module that imports it will have its own set of static members?
Falmarri
2010-08-17 19:38:54
Your edit answered my question, thanks =]
Falmarri
2010-08-17 19:39:24