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

Abstract Methods

The _compareTo method given in Program gif is an abstract method. In particular, the body of the method does nothing. It is expected that the _compareTo method will be overridden in a class derived from the Object class. However, this is only a convention--the Python language does nothing to ensure that the method is overridden. And if the method is not overridden, it remains possible for a Python program to call the abstract method.

To prevent the calling of abstract methods, we introduce the abstractmethod descriptor  class shown in Program gif. The idea is to wrap a function object that is supposed to be an abstract method in an instance of the abstractmethod class as shown on line 17 of Program gif.

   program4463
Program: abstractmethod class definition.

The abstractmethod class does its magic by defining a special __get__ method. Python uses the __get__ method of a class to bind a method to an instance. For example, suppose you have an instance obj of some class Cls. When you call a method like this:

obj.func(*args)
Python effectively does this:
meth = __get__(func, obj, Cls)
meth.__call__(*args)

In Program gif, we implement a __get__ method that returns an instance of the nested abstractmethod.method class. This class in turn implements a __call__ method that raises a TypeError exception. The effect of this is that whenever an abstract method is called an exception is raised.


next up previous index

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