[Tutor] interfaces and abstract classes in python

Kent Johnson kent37 at tds.net
Sun Nov 6 18:42:45 CET 2005


Alex Hunsley wrote:
> Interfaces and abstract classes - I know they don't exist per se in 
> Python. But what are the closest analogues? I've found a few examples, 
> e.g. for an abstract class the following page has a fairly common 
> suggestion:
> 
> http://www.norvig.com/python-iaq.html

Interfaces are generally implicit in Python. For example the docs will sometimes talk about 'file-like objects' which are just objects that implement the same interface as a file object. 'iterable', 'iterator', 'sequence' and 'mapping' are similarly defined by convention or by explicit documentation but not in the language itself. For example the 'iterator protocol' is defined here:
http://docs.python.org/lib/typeiter.html

To define an abstract method I just raise NotImplementedError in the body of the method.

There are a couple of more formalized ways to add support for explicit type requirments to the language. This is a little different from what you asked - these projects allow a client of an object to specify an interface (or protocol) that must be supported by the object.
PyProtocols http://peak.telecommunity.com/PyProtocols.html
Zope Interfaces http://www.zope.org/Wikis/Interfaces/FrontPage

PEP 246 formalizes this notion. It seems to be slated for inclusion in Python 2.5.
http://www.python.org/peps/pep-0246.html

Kent

-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list