|
Data Structures and Algorithms
with Object-Oriented Design Patterns in Python |
Most of the classes described in this book
are derived from a common base class called Object.
As shown in Figure
,
the Object class is an abstract class that extends
the __builtin__.object class

Figure: Object class hierarchy.
Program
gives the Python code
that defines the Object class.

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:
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.