idioms for abstract base classes
Erik Max Francis
max at alcyone.com
Fri Apr 13 12:03:06 EDT 2001
Robin Becker wrote:
> what's the best way to spell an abstract base class so that
> 0) base is B and A inherits from B
>
> 1) doing B() causes an exception
>
> 2) most of the initialisation code is common in B
To mimic abstract base classes, I just define the class as normal and
then define the _methods_ that should be abstract as raising
NotImplementedErrors:
def C:
def f(self):
raise NotImlementedError, "C.f is abstract"
This acts as sufficient warning.
It's not convenient to define C.__init__ as raising a
NotImplementedError since, as you've seen, you may still need C.__init__
to do initialization so that you can call it from derived classes.
I don't think the benefit of strictly following the fully abstract base
class paradigm (e.g., even instantiating such a class raises an
exception) outweighs the inconvenience and lack of clarity.
Furthermore, your solution _still_ defers the exception to runtime, so
in that sense it isn't much better to have the instance raise an
exception when you try to create it, as opposed to raising an exception
when you try to _use_ it.
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ Nothing spoils a confession like repentence.
\__/ Anatole France
Interstelen / http://www.interstelen.com/
A multiplayer, strategic, turn-based Web game on an interstellar scale.
More information about the Python-list
mailing list