idioms for abstract base classes

Alex Martelli aleaxit at yahoo.com
Fri Apr 13 08:19:57 EDT 2001


"Robin Becker" <robin at jessikat.fsnet.co.uk> wrote in message
news:mZW4xJA40t16EwtA at jessikat.fsnet.co.uk...
> 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
    [snip]
> is there a neater way to do this that knows when B is being instantiated
directly?

Pretty easy:

class B:
    def __init__(self):
        if self.__class__ == B:
            raise AbstractClassException, B
        # proceed with initialization tasks

self.__class__ is set to the actual (most-derived) class
that is being instantiated, whether B's __init__ is being
executed explicitly or through inheritance.


Alex






More information about the Python-list mailing list