[SciPy-user] mandatory overriding of class method

Robert Kern rkern at ucsd.edu
Mon Jul 18 15:36:01 CDT 2005

Ryan Krauss wrote:
> I have a general Python question (but I am not subscribed to a general 
> Python list:)-  I intend to use this for technical computing if that 
> makes it any better.

Well, there's always comp.lang.python.

> I want to define a class that I don't the user to be able to use 
> directly and I want to require the user to derive from the class and I 
> want to require that two specifics methods be overridden for the derived 
> class to be valid.  I think in C++ you could define virtual methods so 
> that they had to be overridden.  Is there a way to do this in Python?  I 
> thought about defining the two methods in the base class to do nothing 
> but raise exceptions, but that is kind of a hack and the user would know 
> there was a problem until they tried to call the methods.

They'll know if they read the documentation. The canonical way to do 
this is to have the methods raise NotImplementedError in the base class 
and mention in the class's docstring that it needs to be subclassed and 
those specific methods need to be overwritten.

Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

More information about the SciPy-user mailing list