Python using derived class's method in parent class?

user35288 picture user35288 · Feb 19, 2010 · Viewed 11.1k times · Source

Can I force a parent class to call a derived class's version of a function?

class Base(object):
    attr1 = ''
    attr2 = ''

    def virtual(self):
        pass               # doesn't do anything in the parent class

    def func(self):
        print "%s, %s" % (self.attr1, self.attr2)
        self.virtual()

and a class that derives from it

class Derived(Base):
    attr1 = 'I am in class Derived'
    attr2 = 'blah blah'

    def virtual(self):
        # do stuff...
        # do stuff...

Clearing up vagueness:

d = Derived()
d.func()         # calls self.virtual() which is Base::virtual(), 
                 #  and I need it to be Derived::virtual()

Answer

Alex Martelli picture Alex Martelli · Feb 19, 2010

If you instantiate a Derived (say d = Derived()), the .virtual that's called by d.func() is Derived.virtual. If there is no instance of Derived involved, then there's no suitable self for Derived.virtual and so of course it's impossible to call it.