Pure virtual functions in Python?

Arnaud Delobelle arnodel at googlemail.com
Sat Feb 20 23:02:44 CET 2010


lallous <elias.bachaalany at gmail.com> writes:

> 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"

Why define it if it is virtual?

> # 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.

If you don't define cb in the parent class, it'll work.

-- 
Arnaud



More information about the Python-list mailing list