How do I create static class data and static class methods?
PythonLevel: Intermediate
How do I create static class data and static class methods?
Hints
- Identify object types, mutability and execution order.
- Trace a minimal example: which values and references change?
Answer
Both static data and static methods (in the sense of C++ or Java) are supported in Python.
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 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:
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:
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.
Source and licence: Python 3.14.0 Programming FAQ — Python Software Foundation · PSF-2.0