[Tutor] interfaces and abstract classes in python
Alex Hunsley
lard at tardis.ed.ac.uk
Tue Nov 8 12:12:50 CET 2005
Alan Gauld wrote:
>> Interfaces and abstract classes - I know they don't exist per se in
>> Python.
>
>
> First you need to define what you mean by the terms.
> Every class has an interface - it is the set of messages to which it
> responds.
Yup, I was thinking more in terms of the Java idea, whereby an interface
is declared specifically and then a class claiming to implement it
causes compilation problems if it doesn't properly implement it.
>
> An Abstract class is one which is not intended to be instantiated.
>
> class AbstractClassError(Exception): pass
>
> class Abstract:
> def __init__(self): raise AbstractClassError
Yes, this and the code below with it are very similar to the common
idiom for abstract classes (in Python) that I see quite often.
>
>> But what are the closest analogues? I've found a few examples,
>
>
> Assuming you mean Interface in the Microsoft/Java specific sense of
> the term rather than the simple OOP sense, then an Interface class is
> simply an abstract class with empty methods.
>
> class InterfaceError(Exception): pass
>
> class Interface(Abstract):
> def myMethod(self): pass
> def myOther(self): raise InterfaceErrror
>
> Does that do what you want?
I presume the "def myMethod(self): pass" is just for an 'optional' part
of the interface?
The above code does serve the purpose of making an interface more
explicit, which is helpful. I have seen this use before and I was just
wondering if there was any other common ways to make interfaces more
explicit. Thanks!
Btw, I notice this email list sends the emails with the originator as
the sender, and CC'd to the tutor at python.org address. Is it standard
here to reply to the email address of the sender of the message you're
replying to, as well as the list itself, or should I be trimming out the
sender email and just replying to the list only?
thanks,
alex
More information about the Tutor
mailing list