Pure virtual functions in Python?

Diez B. Roggisch deets at nospam.web.de
Sat Feb 20 11:46:42 EST 2010


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



More information about the Python-list mailing list