-3

how do I know which path exactly super() is going to take in the MRO?

supreme
  • 353
  • 3
  • 14
  • This question should not be closed. The accepted answer to question marked as duplicate does not answer this question. The answer to this question is to look it up with `ClassName.__mro__`. – andyhasit Feb 06 '20 at 02:48

2 Answers2

5

Read: Python's Super Considered Harmful and Python’s super() considered super!.

Those are two great resources that should answer all your questions.

In short though, super() uses a standard Method Resolution Order (MRO) to find the method you ask for. Take a look at this image:

MRO: E, C, A, D, B, object

E inherits from C and D. C inherits from A, and A from object. D inherits from B, and B from object. The red arrows show the MRO that super() uses in its search.

Note that super() does not reference the parent class. Even though A inherits from object and not D, D comes next in MRO. So to answer your question, "next in line" refers to the MRO.

Dan
  • 557
  • 5
  • 12
  • 1
    the red arrow is what I dont understand. why go from e to c and not from e to d, etc., etc.? because e inherits from both c and d, how do I know the route that super() is going to take in the MRO? – supreme Jun 19 '17 at 14:15
  • in other words, why does C get precedence over D? and then goes from C to A, in my mind it should go to either C or D first, in your diagram it goes to C first doesn't find what it needs, I would think it would look in D before moving to A or B. – supreme Jun 19 '17 at 14:33
1

super()

The primary purpose of super() in Python is to call an overridden base class method in a derived class, as super does in other languages. This is usually done so that a derived class method can augment a base class one by calling it before or after its own code, rather than completely replacing it.

class Derived(Base):
    def method(self, arg):
        # Maybe do something here
        super(Derived, self).method(arg)

    # Could so something here as well

The super() function actually works by returning an object of a proxy class that delegates calls to the parent. The advantage of using super() in this case is that you don’t need to explicitly name the base class, which aids maintainability.

The super() function can also be used in more complex multiple inheritance situations, where it can do things like delegate to a sister class

Community
  • 1
  • 1
Hiren Jungi
  • 854
  • 8
  • 20