Friday, June 20, 2008

New-Style Python Classes

Well, I guess you can't really call them new anymore but they are nonetheless an important feature of the Python programming language. It seems that a lot of Python code I look at these days does not use new-style classes. But then again, a lot of it does.

The basic idea of new-style classes is to bridge the gap between primitive solution space and the abstract problem space. As a quick analogy, picture yourself trying to make a bowl of homemade soup. There are several steps involved in the process such as cutting up vegetables, measuring ingredients, mixing ingredients, etc. The common theme here is ingredient. Those with an object-oriented mentality are going to say something like "Ingredient would be a great candidate for a base class for all ingredients in the soup". And I would have to agree.

Now, imagine stove-top cooking as an environment we are working in. While building the soup, we can't conceptualize anything other than what is on the stove-top. In this environment, each ingredient would be considered primitive. The soup inherits all the attributes and behavior from these basic, primitive ingredients. That is the basic idea behind new-style Python classes.

An example of this powerful Python concept:

>>> class book(list):
... pass
...
>>> class page(object):
... name=""
...
>>> my_book=book()
>>> my_book.append(page())
>>> for i in my_book:
... print i
...
<__main__.page>

Here we have two new-style class definitions. The first class, book, inherits from the Python primitive type list. The second class, page, inherits from the Python primitive type object. We then add a page to out book instance, and display all the page objects in out book instance. Pretty simple.

So, why bother generalizing a primitive type when we could just instantiate and use the type directly. That is, why not just create a new Python list and be done with it?

The first reason is one of abstraction. Our book class is just a Python list. It has no real purpose other than to instantiate the Python list object. However, there are several taxonomic list forms like book, bookshelf, the line at the door. They are all lists and Python makes bringing more elegant meaning to our lists an easy task.

The second reason is flexibility and functionality. We can now add our own methods to our lists as well as override the existing list methods.

The possibilities given by new-style Python classes is almost endless.