What is proper way to require a method to be overridden?

Grant Edwards grante at visi.com
Thu Jan 4 23:17:38 EST 2007


On 2007-01-05, Thomas Ploch <Thomas.Ploch at gmx.net> wrote:

>>> I am writing a class that is intended to be subclassed.  What
>>> is the proper way to indicate that a sub class must override a
>>> method?
>> 
>> If any subclass *must* override a method, raise
>> NotImplementedError in the base class (apart from documenting
>> how your class is supposed to be used).
>
> I learn so much from this list. I didn't even know this error existed.

And remember: even if it didn't, you could have created your
own:

------------------------------foo.py------------------------------
class NotImplementedError(Exception):
    pass

def foo():
    print "hi there"
    msg = "there's a penguin on the telly!"
    raise NotImplementedError(msg)
    print "how are you?"
    
foo()
------------------------------------------------------------------

$ python foo.py
hi there
Traceback (most recent call last):
  File "foo.py", line 10, in ?
    foo()
  File "foo.py", line 7, in foo
    raise NotImplementedError(msg)
__main__.NotImplementedError: there's a penguin on the telly!


A few carefully thought-out exceptions can often eliminate the
need for a lot of messy code.

-- 
Grant Edwards                   grante             Yow!  I'll show you MY
                                  at               telex number if you show
                               visi.com            me YOURS...



More information about the Python-list mailing list