Pythonic Abstract Base Class / Interface

Dave Kuhlman dkuhlman at rexx.com
Tue Oct 28 20:31:35 EST 2003


Erik Max Francis wrote:

> Tom Evans wrote:
> 
>> If I have a specific interface which I know is going to be
>> implemented by a number of classes, but there is no
>> implementation commonality between them, what is the preferred
>> form for this in Python?
> ...
>> Is there a clear pythonic way, or does it depend a bit more on
>> the design of the specific program?
> 
> I usually do something like
> 
> class AbstractBase:
>     def __init__(self):
>     if self.__class__ is AbstractBase:
>         raise NotImplementedError
> 
[snip]

If you expect anyone else (or yourself when you've forgotten this
code) to implement another derived class (to implement the
interface), then you will also want to add doc strings to each of
the methods, so that an implementer of your interface knows what
the requirements are for each parameter, return values, etc. 
Implementing the (empty) base class is a good way to provide
documentation on your interface.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
dkuhlman at rexx.com




More information about the Python-list mailing list