Pure virtual functions in Python?

lallous elias.bachaalany at gmail.com
Sun Feb 21 09:22:56 CET 2010


On Feb 20, 6:08 pm, "Martin v. Loewis" <mar... at v.loewis.de> wrote:
> >> class C1:
>
> >>      # Pure virtual
> >>      def cb(self, param1, param2):
> >>          """
> >>          This is a callback
>
> >>          @param param1: ...
> >>          @param param2: ...
> >>          """
> >>          raise NotImplementedError, "Implement me"
>
> >> # 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.
>
> That's not true. Currently, the hasattr() call would report that cb is
> available, when it is actually not implemented. It would be possible to
> do something like
>
>   if hasattr(c, 'cb') and not is_pure(c.cb):
>       c.cb("Hello", "World")
>
> is_pure could, for example, look at a function attribute of the
> callback. You'd write something like
>
>   @pure_virtual
>   def cb(self, param1, param2):
>       not_implemented
>
> Regards,
> Martin

Hello Martine,

Can you elaborate more on how to use the mechanism you described?

Thanks,
Elias



More information about the Python-list mailing list