Skip to content Skip to sidebar Skip to footer

Static Class Members Python

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 thi

Solution 1:

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'

Post a Comment for "Static Class Members Python"