Static Data and Static Methods and Decorators

In some situations it is useful to have data that is associated with a class as a whole rather than with its instances. For example, if we have a Balloon class, we might want to know how many unique colors have been used:

class Balloon(object):

unique_colors = set()

self.color = color Balloon.unique_colors.add(color)

@staticmethod def uniqueColorCount():

return len(Balloon.unique_colors)

@staticmethod def uniqueColors():

return Balloon.unique_colors.copy()

Static data is created inside a class block, but outside of any def statements. To access static data, we must qualify the name, and the easiest way to do so is by using the class name, as we do in the Balloon class's static methods. We will see static data and methods in more realistic contexts in the next subsection.

The @staticmethod is a decorator. A decorator is a function that takes a function as an argument, wraps it in some way, and assigns the wrapped function back to the original function's name, so it has the same effect as writing this:

def uniqueColors():

return Balloon.unique_colors.copy() uniqueColors = staticmethod(uniqueColors)

The @ symbol is used to signify a decorator. The staticmethod() function is one of Python's built-in functions.

We can use more than one decorator. For example, a suitable decorator could be written to instrument functions and methods, or to log each time a method is called. For example:

@logger @recalculate def changeWidth(self, width): self.width = width

Here, whenever the object's width is changed two decorators are applied: log-ger(), which might record the change in a log file or database, and recalcu-late(), which might update the object's area.

In addition to static methods, Python also supports "class methods". These are similar to static methods in that they do not have a self first argument, and so can be called using a class or an instance. What distinguishes them from static methods is that they have a Python-supplied first argument, the class they are called on. This is conventionally called cls.

+1 0

Post a comment