[Tutor] Interfaces in Python

Alan Gauld alan.gauld at freenet.co.uk
Thu Jun 15 02:06:38 CEST 2006


> I am learning Python and relating to my knowledge of Java... What is 
> (Is there?) the equivalent of Java interfaces in Python?  How could 
> I write my own?

There is no direct equivalent.
Interfaces are implicit in Python, they are only really necessary in
statically  typed languages. Dynamically typed languages rely on
"Duck typing" and therefore the concept of an interface is not 
required.
( Interfaces are a serious impediment to good OO design IMHO, they
imply an element of  fore knowledge of how a class will be used and
involve additional work that often is not needed. They are basically
a flexibility point introduced to mitigate against change in a static
typing environment)

A good example of duck typing is the concept of a "file like object" 
which is
used in several places in Python. It basically means any object which
has the same message protocol as a file. This is the saqme style of
OOP used in SmallTalk, Lisp and ObjectiveC (although the latter also
supports statically typed interfaces too)

[ It is possible to create abstract classes in Python however using 
some
sneaky tricks but the easiest way is probably just to throw an 
exception
in the init method! Abstract classes are an alternative way to view
interfaces - interaces are cut-down abstract classes...]

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list