Missing interfaces in Python...

olsongt at verizon.net olsongt at verizon.net
Tue Apr 18 13:50:54 EDT 2006


redefined.horizons at gmail.com wrote:
> I'm coming from a Java background, so please don't stone me...
>
> I see that Python is missing "interfaces". The concept of an interface
> is a key to good programming design in Java, but I've read that they
> aren't really necessary in Python. I am wondering what technique I can
> use in Python to get the same benefits to a program design that I would
> get with interfaces in Java.
>
> For example, if I want to have a program with a Car object, and a Bus
> object. I want both of these objects to present a common group of
> methods that can be used by Mechanic objects, but slightly different
> methods that can be used by Driver objects.
>
> In Java I would accomplish this by defining an IFixable interface that
> would be implemented by both the Car and Bus objects. Mechanic objects
> would work with any object implementing this interface.
>
> How would I approach this problem in Python? I think I would use an
> abstract class instead of an interface for IFixable, since Python
> supports multiple inheritance, but I'm not sure this is correct.
>
> Thanks for any suggestions.
>
> Scott Huey

Everyone is getting off track here.

Java has interfaces because it doesn't support multiple inheritance.
Python supports MI, so you don't need to use the seperate concept of an
interface.  You're right that an abstract class is the equivilent of an
interface.  Just create a ABC that raises NotImplementedExceptions for
each of the methods, and use that class as one of the base classes.  Of
course, like a lot of stuff in python, this won't throw an exception at
'compile-time', only when you try to invoke a method that has no
implemenation.

The general wisdom is that Abstract Base Classes aren't pythonic
though.  If you want to  be pythonic, just implement the methods for
your 'interface', and (if necessary) check for their existance with
hasattr before calling (or even just call the method and you'll get an
attribute error anyway).  This is referred to as duck-typing.  If it
looks like a duck, and quacks like a duck, then for all practical
purposes it supports the 'duck' interface.




More information about the Python-list mailing list