Pure virtual functions in Python?

Rami Chowdhury rami.chowdhury at gmail.com
Sat Feb 20 12:19:27 EST 2010


On Saturday 20 February 2010 11:46:42 Diez B. Roggisch wrote:
> Am 20.02.10 17:12, schrieb lallous:
> > Hello
> >
> > How can I do something similar to pure virtual functions in C++ ?
> >
> > Let us consider this:
> >
> > class C1:
> >
> >      # Pure virtual
> >      def cb(self, param1, param2):
> >          """
> >          This is a callback
> >
> >          @param param1: ...
> >          @param param2: ...
> >          """
> >          raise NotImplementedError, "Implement me"
> >
> > # Implementation w/o a 'cb', thus 'cb' should not be used
> > class C2(C1):
> >      def __init__(self):
> >          pass
> >
> > # Implementation w/ 'cb', thus 'cb' can be used
> > class C3(C1):
> >      def __init__(self):
> >          pass
> >
> >      def cb(self, param1, param2):
> >          print "i am c3 cb"
> >
> > # Dispatcher function that calls 'cb' only if 'cb' is implemented in
> > child classes
> > def dispatcher(c):
> >      if hasattr(c, 'cb'):
> >          c.cb("Hello", "World")
> >
> > dispatcher(C2())
> > dispatcher(C3())
> >
> > What I want is the ability to have the dispatcher() not to call 'cb'
> > if it was not implemented in one of the child classes.
> >
> > Please advise.
> 
> There is nothing more beyond that what you already did. You can raise a
> NotImplementedError for classes that don't implement the method. That's it.
> 
> Diez
> 

Perhaps you could use an easier-to-ask-forgiveness-than-permission idiom?

def dispatcher(c):
	try:
		c.cb("Hello", "World")
	except NotImplementedError:
		pass



----
Rami Chowdhury
"Passion is inversely proportional to the amount of real information 
available." -- Benford's Law of Controversy
408-597-7068 (US) / 07875-841-046 (UK) / 01819-245544 (BD)



More information about the Python-list mailing list