Skip to content Skip to sidebar Skip to footer

Python Using Derived Class's Method In Parent Class?

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

Solution 1:

If you instantiate a Derived (say d = Derived()), the .virtual that's called by d.func()isDerived.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.

Solution 2:

It isn't impossible -- there is a way around this actually, and you don't have to pass in the function or anything like that. I am working on a project myself where this exact problem came up. Here is the solution:

classBase(): # no need to explicitly derive object for it to work
    attr1 = 'I am in class Base'
    attr2 = 'halb halb'defvirtual(self):
        print"Base's Method"deffunc(self):
        print"%s, %s" % (self.attr1, self.attr2)
        self.virtual()

classDerived(Base):
    attr1 = 'I am in class Derived'
    attr2 = 'blah blah'def__init__(self):
  # only way I've found so far is to edit the dict like this
        Base.__dict__['_Base_virtual'] = self.virtual

    defvirtual(self):
        print"Derived's Method"if __name__ == '__main__':
    d = Derived()
    d.func()

Post a Comment for "Python Using Derived Class's Method In Parent Class?"