Abstract base classes can still be handy in Python. In writing an abstract base class where I want every subclass to have, say, a spam()
method, I want to write something like this:
class Abstract(object):
def spam(self):
raise NotImplementedError
The challenge comes in also wanting to use super()
, and to do it properly by including it in the entire chain of subclasses. In this case, it seems I have to wrap every super
call like the following:
class Useful(Abstract):
def spam(self):
try:
super(Useful, self).spam()
except NotImplementedError, e:
pass
print("It's okay.")
That's okay for a simple subclass, but when writing a class that has many methods, the try-except thing gets a bit cumbersome, and a bit ugly. Is there a more elegant way of subclassing from abstract base classes? Am I just Doing It Wrong?
You can do this cleanly in python 2.6+ with the abc module:
import abc
class B(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def foo(self):
print 'In B'
class C(B):
def foo(self):
super(C, self).foo()
print 'In C'
C().foo()
The output will be
In B
In C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With