Is this Pythonic?

Erik Max Francis max at alcyone.com
Mon Aug 1 17:07:46 EDT 2005


phil hunt wrote:

> Suppose I'm writing an abstract superclass which will have some 
> concrete subclasses. I want to signal in my code that the subclasses 
> will implement certan methods. Is this a Pythonic way of doing what 
> I have in mind:
> 
> class Foo: # abstract superclass
>    def bar(self):
>       raise Exception, "Implemented by subclass"
>    def baz(self):
>       raise Exception, "Implemented by subclass"
> 
> class Concrete(Foo):
>    def bar(self):
>       #...actual implemtation...
>    def baz(self):
>       #...actual implemtation...

Yes, but raise NotImplementedError instead of Exception.  Another trick 
you can use is to prevent people from instantiating the abstract class:

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

	    def bar(self):
	        raise NotImplementedError

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Everything's gonna be all right / Everything's gonna be okay
   -- Sweetbox



More information about the Python-list mailing list