Abstract base classes are deep magic. Periodically I implement something using them and am amazed at my own cleverness, very shortly afterwards I find myself completely confused by my own cleverness (this may well just be a personal limitation though).
Another way of doing this (should be in the python std libs if you ask me) is to make a decorator.
def abstractmethod(method):
"""
An @abstractmethod member fn decorator.
(put this in some library somewhere for reuse).
"""
def default_abstract_method(*args, **kwargs):
raise NotImplementedError('call to abstract method '
+ repr(method))
default_abstract_method.__name__ = method.__name__
return default_abstract_method
class Shape(object):
def __init__(self, shape_name):
self.shape = shape_name
@abstractmethod
def foo(self):
print "bar"
return
class Rectangle(Shape):
# note you don't need to do the constructor twice either
pass
r = Rectangle("x")
r.foo()
I didn't write the decorator. It just occurred to me someone would have. You can find it here: http://code.activestate.com/recipes/577666-abstract-method-decorator/ Good one jimmy2times. Note the discussion at the bottom of that page r.e. type safety of the decorator. (That could be fixed with the inspect module if anyone was so inclined).