I want to ensure that any class that is derived from my class overrides certain methods. If they are not overridden I want to raise a NotImplementedError as soon as possible after compiling begins, rather than when one of the methods are called.
I've found that I can do it with a metaclass like so:
class MetaBaseClass(type):
# list of method names which should be overridden
to_override = ['method_a', 'method_b']
def __init__(cls, name, bases, dct):
for methodName in cls.to_override:
if methodName not in dct:
raise NotImplementedError('{0} must override the {1} method'.format(name, methodName))
super(MetaBaseClass, cls).__init__(name, bases, dct)
class BaseClass(object):
__metaclass__ = MetaBaseClass
def method_a(self):
pass
def method_b(self):
pass
This will raise the error at class definition time if method_a
or method_b
aren't overridden by class derived from BaseClass.
Is there a better way to do this?