Data Structures and Algorithms with Object-Oriented Design Patterns in Python
next up previous index

Abstract Objects

Most of the classes described in this book are derived from a common base class called Object. As shown in Figure gif, the Object class is an abstract class that extends the __builtin__.object class

   figure4395
Figure: Object class hierarchy.

Program gif gives the Python code that defines the Object class.

   program4404
Program: Object class definition.

Notice that the Object class defines a method called __cmp__. This instance method takes a specified object and compares it with the given object instance. The method returns an integer that is less than, equal to, or greater than zero depending on whether this object instance is less than, equal to, or greater than the specified object instance obj, respectively.

The __cmp__ method is special in several respects. First, it is the method that is called by the standard cmp function. I.e., given two Object instances, the following statements are equivalent:

result = cmp(obj1, obj2)
result = obj1.__cmp__(obj2)
Second, the __cmp__ method is automatically called whenever one of the comparison operators, (<, <=, ==, !=, >, and >=) is used to compare two Object instances. For example, the following statements are equivalent:
result = obj1 < obj2
result = obj1.__cmp__(obj2) < 0

Notice how the __cmp__ method of the Object class is implemented. When comparing two object instances, obj1 and obj1, the comparison works as follows:

  1. If the class of obj1 is a subclass of the class of obj2, then the result of the comparison is obj1._compareTo(obj2).
  2. If the class of obj2 is a subclass of the class of obj1, then the result of the comparison is obj2._compareTo(obj1).
  3. If the classes are unrelated, the the result is obtained by comparing the names of the classes.
The _compareTo method is declared to be an abstract method. This means that it one must be provided in the implementation of every concrete class derived from the Object base class. The implementation of the _compareTo method for a given class is simplified because it will always be the case that the given class is a subclass of the class of the _compareTo argument.

The use of polymorphism in the way shown gives the programmer enormous leverage. The fact most objects are derived from the Object base class, together with the fact that every concrete class must implement an appropriate _compareTo method, ensures that the comparison operators can be used to compare any pair of Objects and that the comparisons always work as expected.


next up previous index

Bruno Copyright © 2003, 2004 by Bruno R. Preiss, P.Eng. All rights reserved.