Pure virtual functions in Python?

lallous elias.bachaalany at gmail.com
Sat Feb 20 17:12:01 CET 2010


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.



More information about the Python-list mailing list