Skip to content
All apps

Where does Python find the method?

About this app

A tower of object, Wettkampf, Lauf and object: for w.tempo(), print(w) or l.platz a search beam climbs station by station, and the first match wins. tempo lives only in Lauf, all attributes sit in the one object, and super() continues the search one level up. Switching methods off shows which version of __str__ takes over, all the way up to object.

How Python finds attributes and methods

When you write w.name, Python first looks in the object itself, then in its class, then in the base class and finally in object, the common root of all classes. The first hit wins. A subclass therefore does not get a copy of the inherited methods; they are simply found further up. If the subclass overrides a method, the base version is not deleted, only hidden earlier in the search. super() continues the search one level above the current class. All attributes live in the one object, not in the classes.

What the app shows

A tower of cards: at the bottom the object w with distanz, zeit and platz, above it the classes Wettkampf (competition), Lauf (run) and object. Next to it an object l of class Lauf. For a chosen expression a search beam climbs station by station and stops at the first hit, and the result appears at the bottom. The code comes from a short program with Lauf and its subclass Wettkampf.

Try it yourself

Pick expressions such as w.tempo(), print(w), w.platz, l.platz or isinstance(w, Lauf) and follow the lookup path. For print(w) you see two lookups, because Wettkampf.__str__ calls the version in Lauf via super(). Switch off Wettkampf.__str__ and then Lauf.__str__ too: in the end object takes over and prints only the object address.

Frequently asked questions

In what order does Python look up methods?
First in the object, then in its class, then in the base classes and finally in object. With multiple inheritance the method resolution order (MRO) defines the order; you can inspect it with Class.__mro__.
What does super() do in Python?
super() gives access to the next class above the current one in the lookup order. super().__init__(d, z) therefore calls the base class constructor so it can set its attributes before the subclass adds its own.
Does a subclass get a copy of the methods?
No. Methods stay in the class where they are defined. A subclass only refers to its base class, and the lookup finds inherited methods there. Overriding hides the base version without deleting it.
What does Where does Python find the method? show?
A tower of object, Wettkampf, Lauf and object through which a search beam climbs for different expressions. You can switch off individual __str__ methods and see which version applies instead.

Subject: Computer science

More from Computer science

A VisuApp by heyprof: interactive, free in your browser, no sign-up. What is a VisuApp? · All apps