EDIT: My assumptions were wrong; the code below does in fact work like I wanted it to. The behaviour I was observing turned out to be caused by another bit of the code I was working with that I overlooked because it looked completely unrelated.
So I have some code structured like this:
class B(object):
def foo(self):
print "spam"
def bar(self):
do_something()
self.foo()
do_something_else()
class C(B):
def foo(self):
print "ham"
def bar(self):
super(C, self).bar()
print "eggs"
c = C()
c.bar()
This would do_something(), print “spam”, do_something_else(), and then print “eggs”. However, what I want to do is do_something(), print “ham”, do_something_else(), and then print “eggs”. In other words, I want to call B’s bar method from C’s bar method, but I want it to call C’s foo method, not B’s.
Is there a way to do this? Note that in the actual code I’m dealing with, both the B class and the code that actually calls c.bar() are part of an evolving third-party library, so mucking with that would be a last resort.
The code you have posted does what you want.
When
B.barcallsself.foo()whenselfis an object of typeC, it will callC.foo.This works because
self.foois looked up first onselfthen onself‘s actual type’s method-resolution-order C3-linearised class-and-base-classes tuple (here(C, B, object)). This will returnC.foobeforeB.foo.