Next / Previous / Contents / TCC Help System / NM Tech homepage

11.6. Abstract data types in Python

We saw how you can use a two-element tuple to group a snail's time and name together. However, in the real world, we might need to track more than two attributes of an instance.

Suppose Malek wants to keep track of more attributes of a snail, such as its age in days, its weight in grams, its length in millimeters, and its color. We could use a six-element tuple like this:

(87.3, 'Judy', 34, 1.66, 39, 'tan')

The problem with this approach is that we have to remember that for a tuple T, the time is in T[0], the name in T[1], the age in T[2], and so on.

A cleaner, more natural way to keep track of attributes is to give them names. We might encode those six attributes in a Python dictionary like this:

T = { 'time':87.3, 'name':'Judy', 'age':34, 'mass':1.66,
       'length':39, 'color':'tan'}

With this approach, we can retrieve the name as T['name] or the weight as T['mass']. However, now we have lost the ability to put several of these dictionaries into a list and sort the list—how is Python supposed to know which dictionary comes first? What we need is something like a dictionary, but with more features. What we need is Python's object-oriented features.

Now we're to look at actual Python classes and instances in action.