Abstract Base Classes

Mike Meyer mwm at mired.org
Thu Nov 10 23:20:42 EST 2005


Ben Finney <bignose+hates-spam at benfinney.id.au> writes:
> I've tried doing this in the __init__():
>
>     class FooException(Exception):
>         """ Base class for all FooModule exceptions """
>         def __init__(self):
>             raise NotImplementedError, \
>                 "%s is an abstract class for exceptions" % self.__class__
>
> When I use this, I discovered to my horror that the subclasses were
> calling FooException.__init__ -- which I though wasn't supposed to
> happen in Python!
> It's also rather semantically weird, to my eye.

Calling __init__ is handled just like any other method (this is a good
thing), so if your subclasses fail to define __init__, the version in
the superclass gets called. If it were otherwise, every class would
have to declare __init__ just to call super(cls, self).__init__.

> Can I do something tricky with checking base classes in the
> FooException.__init__() ?

Untested:

class FooException(Exception):
      def __init__(self):
          if self.__class__ == FooException:
             raise NotImplementedError,
                   "FooException is an abstract class for exceptions"

Personally, I find this unpythonic. FooException doesn't contribute
anything, and has no real reason for existing. If Python did static
type checking, it would make sense, but python doesn't, so it doesn't.

If you hadn't referenced interfaces, I'd suspect you might be planing
on catching all FooExceptions in a try:/except:. I'm not sure you'll
be able to list an interace in an except clause when they come to
exist, though.

      <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list