Pythonic Abstract Base Class / Interface
Alex Martelli
aleax at aleax.it
Tue Oct 28 09:34:23 EST 2003
Tom Evans wrote:
> My basic question:
> 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?
The normal Python approach is currently to just rely on signature-based
polymorphism -- use inheritance to share implementation, but if you
have no implementation to share, there's no real reason to inherit.
Of course, people coming from languages where inheritance reigns will
not accept that easily and refer to such issues as:
-- in your 'interface class' you can implement the methods as raising
NotImplementedError, which will be clearer than the AttributeError
that happens upon trying to call the method on an instance of a
class that's meant to implement the interface but forgot the
method in question
-- inheritance is ALMOST always centered on sharing implementation --
in the case of exception handling, though, inheritance trees do matter
-- if you inherit you can typetest with isinstance rather than just
featuretest with hasattr (to me, that's a DEFECT of inheritance:-)
If you do have any useful features -- most often Template Method
design patterns -- to share among (some of) your concrete classes,
then by all means use inheritance for that. But, otherwise, I think
that keeping documentation in comments and docstring, and using
other language constructs (including inheritance0 for substantial
purposes and not "just to document things", is a preferable approach.
Alex
More information about the Python-list
mailing list