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

belinda thom bthom at cs.hmc.edu
Fri Jan 5 00:59:13 EST 2007


On Jan 4, 2007, at 9:28 PM, Carl Banks wrote:

> jeremito 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?
>
> You can't (easily).
>
> If your subclass doesn't override a method, then you'll get a big fat
> AttributeError when someone tries to call it.  But this doesn't stop
> someone from defining a subclass that fails to override the method.
> Only when it's called will the error show up.  You can, as others have
> noted, define a method that raises NotImplementedError.  But this  
> still
> doesn't stop someone from defining a subclass that fails to override
> the method.  The error still only occurs when the method is called.
>
> There are some advantages to using NotImplementedError:
>
> 1. It documents the fact that a method needs to be overridden
> 2. It lets tools such as pylint know that this is an abstract method
> 3. It results in a more informative error message
>
> But, in the end, if someone wants to define a class that defiantly
> refuses to declare a method, you can't stop them.

This is the con of a dynamic language...



More information about the Python-list mailing list