Missing interfaces in Python...

Roy Smith roy at panix.com
Mon Apr 17 17:51:41 EDT 2006


<redefined.horizons at gmail.com> wrote:
> 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.

Python is a very dynamic language.  Java is a very static language.
What that means is that in Java (like C++), you do a lot of error
checking at compile time.  That's what interfaces are all about.  In
Python, you do almost no error checking (beyond basic language syntax)
at compile time, and do everything at run time.  For the most part,
this means wrapping things in try blocks and catching exceptions.

>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.

Well, let's say your IFixable interface in Java would have included
changeTire(), rechargeBattery(), and adjustBrakes() methods.  In
Python, I'd just go ahead and implement those methods for both Car and
Bus classes.  All Java's interface mechanism does for you is provide
some compile-time checking that those methods are implemented.  In
Python, you would just call those methods when appropriate, and catch
any NameError exception that would happen if it turns out there is no
such method.

Consider that in Python, an object can have methods added to it after
it is created.  It's entirely possible that the Car class has no
changeTire() method, but one would be added to each Car instance
sometime before the first place it might be called.  Consider
something like:

    if self.owner.hasRoadsideAssistance():
        self.changeTire = callForHelp
    elif self.owner.canFixThings:
        self.changeTire = getHandsDirty

Now, calling myCar.changeTire() could end up calling callForHelp(), or
calling getHandsDirty(), or throwing NameError is no way exists to get
the tire fixed.  Maybe that's what makes sense in your application.



More information about the Python-list mailing list