We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How do I create static class data and static class methods?

Static data (in the sense of C++ or Java) is easy; static methods (again in the sense of C++ or Java) are only supported for new-style classes.

For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment:

class C:
    count = 0   # number of times C.__init__ called

    def __init__(self):
        C.count = C.count + 1

    def getcount(self):
        return C.count  # or return self.count

c.count also refers to C.count for any c such that isinstance(c, C) holds, unless overridden by c itself or by some class on the base-class search path from c.__class__ back to C.

Caution: within a method of C, an assignment like self.count = 42 creates a new and unrelated instance attribute named “count” in self’s own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not:

C.count = 314

Static methods are possible when you’re using new-style classes:

class C:

    @staticmethod
    def static(arg1, arg2, arg3):
        # No 'self' parameter!
        ...

However, a far more straightforward way to get the effect of a static method is via a simple module-level function:

class C:
    ...    

def getcount():
    return C.count

If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation.

CATEGORY: programming