pure virtual functions in python

Erik Max Francis max at alcyone.com
Sun Jan 12 18:39:03 EST 2003


polux wrote:

> how to emulate them ?
> I mean, how to force a user to redifine some functions in a derivated
> class ?

I usually emulate them by throwing a NotImplmementedError.  For classes
which are "abstract" -- that is, have at least one "pure virtual method"
-- you can use something like

	class AbstractSomething:
	    def __init__(self, ...):
	        if self.__class__ is AbstractSomething:
	            raise NotImplementedError
	        ...

	class ConcreteSomething(AbstractSomething):
	    def __init__(self, ...):
	        AbstractSomething.__init__(self, ...)

This will prevent people from creating AbstractSomethings directly, but
they'll have no problem calling the AbstractSomething.__init__ method
from a subclass.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ A good indignation brings out all one's powers.
\__/ Ralph Waldo Emerson
    Lsystem / http://www.alcyone.com/pyos/lsystem/
 A Lindenmayer systems explorer in Python.




More information about the Python-list mailing list