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.

Was this article helpful?

+1 0
YouTube Saturation

YouTube Saturation

Uncover The Instant Traffic System That Will TRIPLE Your Income Overnight While Putting You In Direct Contact With THOUSANDS Of Hungry Buyers. How to generate instant traffic to your website, easily! Siphon high quality, ultra-targeted traffic to your offers. The easiest way to dominate your market with lase targeted video based campaigns. These video ads will suck in customers by the minute, driving your message out to a global audience of buyers.

Get My Free Ebook

Post a comment