idioms for abstract base classes
Steve Purcell
stephen_purcell at yahoo.com
Fri Apr 13 07:51:58 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
On further reflection, the key thing is that an abstract class has one or
more methods that *must* be overridden. So you can explicitly cripple
those methods:
>>> class B:
... "Abstract base class: subclasses must define method blah"
... def __init__(self):
... # ...
... pass
... def blah(self):
... raise "B.blah must be overridden"
...
>>> class A(B):
... def blah(self):
... print 'A.blah'
...
>>> B().blah()
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in blah
B.blah must be overridden
>>> A().blah()
A.blah
Or implicitly crippling abstract methods by not defining them in the
base class:
>>> class B:
... "Abstract base class: subclasses must define method blah"
... pass
...
>>> B().blah()
Traceback (innermost last):
File "<stdin>", line 1, in ?
AttributeError: blah
This also works if the base class is abstract with respect to attributes:
>>> class B:
... "subclasses must define attribute KNOWN_KEYS"
... def __init__(self):
... self.keys = {}
... for k in self.KNOWN_KEYS: self.keys[k] = None
...
>>> B()
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in __init__
AttributeError: KNOWN_KEYS
>>> class A(B):
... KNOWN_KEYS = ('one', 'two', 'three')
...
>>> A()
<__main__.A instance at 8070e20>
>>>
Personally, I would not bother enforcing abstractness explicitly.
The base class documentation should say "abstract"; either people follow
the documentation in order to make a correct subclass, or their code breaks
and they then read the documentation!
-Steve
--
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo
More information about the Python-list
mailing list