[Tutor] interfaces and abstract classes in python

Alex Hunsley lard at tardis.ed.ac.uk
Tue Nov 8 12:16:14 CET 2005


Kent Johnson wrote:

>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
>  
>
Yup, I've run into the __getitem__ etc. methods that you can overload 
which is pretty handy stuff.

>To define an abstract method I just raise NotImplementedError in the body of the method.
>  
>
Ah, ok. This appears to be the pythonic way.

>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
>  
>
I've had a look at these before and although they look relevant, I'm 
more interested in the core python language at the moment, and what that 
can do itself.

>PEP 246 formalizes this notion. It seems to be slated for inclusion in Python 2.5.
>http://www.python.org/peps/pep-0246.html
>  
>
This PEP looks like a good idea!
thanks
alex

>Kent
>
>  
>




More information about the Tutor mailing list