Abstract class
Roy Smith
roy at panix.com
Mon Sep 15 08:58:54 EDT 2008
Maric Michaud <maric at aristote.info> wrote:
> The only way to do this is to call in the __init__ at least one of the
> methods raising NotImplementedError, probably creating a dummy one for
> this purpose, and still it doesn't satisfy with the constraint that
> *all* abstract methods must be implemented in concrete classes.
I wouldn't actually *call* the method (because of possible side-effects),
but you could certainly check that they exist and are callable:
class Base:
"""An abstract base class. You must define methods f(),
g(), and h() in any subclasses of this.
"""
def __init__(self):
try:
assert callable(self.f)
assert callable(self.g)
assert callable(self.h)
except:
raise NotImplementedError # or something more specific
Of course, this assumes that you write:
class Derived(Base):
def __init__(self):
Base.__init__(self)
There's no way (that I can think of :-)) to *force* you to call
Base.__init__() from Derived.__init__().
This is all a bit silly, however. If you want type bondage, use a language
that gives you type bondage (C++ and Java being two obvious examples).
More information about the Python-list
mailing list