How about "pure virtual methods"?

Mike Meyer mwm at mired.org
Sat Dec 25 22:42:45 EST 2004


Noam Raphael <noamr at remove.the.dot.myrea.lbox.com> writes:

> The current Python doesn't really support this concept. You can write
> in the __new__ of such a class something like "if cls ==
> MyAbstractClass: raise TypeError", but I consider this as a patch -
> for example, if you have a subclass of this class which is abstract
> too, you'll have to write this exception code again. Before
> introducing another problem, let me quote Alex:

You can do *much* better than that. You can finger the class that the
object is an instance of. You don't need a new language construct to
do it, either:

 >> class A:
 ..  def virtualmethod(self):
 ..    raise NotImplementedError("virtualmethod not implemented in class %s" \
                                                   % self.__class__.__name__)
 .. 
 >> class B(A):
       pass
 .. 
 >> b = B()
 >> b.virtualmethod()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in virtualmethod
NotImplementedError: virtualmethod not implemented in class B
 >> 

I think that error message pinpoints the class of the instance that's
missing the virtual method, which is as good as your proposal would
do, adequately documents that this method needs to be implemented by
subclasses, and has the advantage that you can instantiate only part
of the interface to an abstract class if you only need part of it.

   <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list