0
class Foo1:
    def hi(self, name):
        print('Oh hi there %s.' % name)

class Foo2:
    def hi(self, name):
        print('Hi %s, how ya doing?' % name)

class Bar(Foo1, Foo2):
    def hi(self, name):
       super(Bar, self).hi(name)

bar = Bar()
bar.hi('John')

Outputs:

Oh hi there John.

How do you access Foo2's super method instead from Bar, other than just swapping the order of "Foo1, Foo2"?

gornvix
  • 3,154
  • 6
  • 35
  • 74
  • Does this answer your question? [super function in Multiple inheritance in python](https://stackoverflow.com/questions/47194629/super-function-in-multiple-inheritance-in-python) – Green Cloak Guy Sep 17 '20 at 13:14
  • That's about init which is different I guess because there is always a super init. – gornvix Sep 17 '20 at 13:34

1 Answers1

3

If you want to bypass the normal method resolution order, you're stuck with hacks. Either:

  1. Pretend to be the class just before the one you really want in the MRO:

    def hi(self, name):
        super(Foo1, self).hi(name)  # I'm really Bar's method, but lying to say I'm Foo1's
    
  2. Explicitly invoke the class you care about (manually passing self):

    def hi(self, name):
        Foo2.hi(self, name)  # Looking it up directly on the class I want
    

A note: If you're using Python 3 and want the normal MRO, you don't need to pass arguments to super() at all, this will invoke Foo1.hi just fine:

   def hi(self, name):
       super().hi(name)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Your first method causes an error because Foo1 has no super hi. The second method is fine. – gornvix Sep 17 '20 at 13:24
  • 1
    @gornvix: It works fine if you define that method in `Bar` (which has both `Foo1` and `Foo2` as parents). `super()` traverses the MRO of `self` (`self` is a `Bar`) using the marker class to say "start looking after this". The MRO of `Bar` is `Bar, Foo1, Foo2, object`, so when you say "start after `Foo1`" it finds `Foo2`, even though `Foo1` knows nothing about it. [Try it online!](https://tio.run/##jc6xCgIxDAbgvU@R5WgL5UDdBBEcRFx8hurlbOFsSluRe/ra3qmLg2YKyZ@P@DEZcqucL4OOEfZEizWDUh32YKyIOPQKnL6hnOe1fLAuCX4yJQHJYEBoYsuhmYOMfbDl39jBFkOBoQeMGjqy7rr9Enc6iPqimmz5E493j@@LupdtCb7Esw6wmURZ@7rhRzKOy5yf) – ShadowRanger Sep 17 '20 at 13:43
  • Oops, sorry, my bad. – gornvix Sep 17 '20 at 14:04