Inheritance and method resolution
Two extensions both need to change a report title. Follow one method call through four classes to see how Python combines them. Read the classes and composition lessons first.
On this page
Read the model
A subclass can reuse a method from a base class. When several classes supply the same name, Python searches the method resolution order (MRO). Inside a method, super() continues that search after the class that defined the current method, using the type of the actual object.
Follow the example
class Base:
def title(self):
return "sales"
class Prefix(Base):
def title(self):
return "Q1 " + super().title()
class Upper(Base):
def title(self):
return super().title().upper()
class Report(Upper, Prefix):
pass
print(Report().title())The order is Report, Upper, Prefix, Base, object. Upper asks for the next title. Prefix asks Base for “sales” and prepends “Q1 ”. Upper then capitalizes the complete result, producing Q1 SALES. The calls travel down the order and the results return in reverse.
Change one condition
Change the prefix to “draft ” and swap the bases of Report. Predict both results. With Upper first you get DRAFT SALES. With Prefix first only “sales” passes through Upper, giving draft SALES. If either method returns immediately, later methods never participate.