Static in python

By: Python Documentation Team Viewed: 153201 times  Printer Friendly Format    

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 since Python 2.2:

class C:
    def static(arg1, arg2, arg3):
        # No 'self' parameter!
    static = staticmethod(static)

With Python 2.4’s decorators, this can also be written as

class C:
    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.

Most Viewed Articles (in Python )

Latest Articles (in Python)

Comment on this tutorial