Interview Questions

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

Python Questions and Answers

(Continued from previous question...)

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 not supported directly.

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 vrbl 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:
def static(arg1, arg2, arg3):
# No 'self' parameter!
static = staticmethod(static)

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

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.

(Continued on next question...)

Other Interview Questions