Lesson · Object-Oriented Python
Inheritance
55 min readInheritance
Inheritance lets a class specialize another class, but it also couples their interfaces and behavior. Use it when the subtype relationship is real, and understand how `super()` participates in cooperative method calls.
Learning goals
- Explain what
class Dog(Animal)creates: a new class whose MRO placesDogbeforeAnimalfor every lookup. - Trace
Dog().speak()to the overriding method and say whyAnimal.speaknever runs. - Predict what
announce(Dog())prints and whyannounceworks with any object that answersspeak. - Read
super()as "continue the search after the current class in the MRO" rather than "call the parent". - State what
isinstance(dog, Animal)andissubclass(Dog, Animal)each answer.
Mental model
Inheritance changes where lookup starts, not how it works: the subclass is simply earlier in the MRO. super() is not a reference to the parent class; it is a pointer to the next class in that same order.
Mental model
read it top to bottom
Dog().speak() ↓ lookup starts on type(dog) = Dog Dog.speak found → returns "woof" (Animal.speak never runs) ↓ if it were missing search continues along Dog.__mro__ → Animal → object ↓ still missing AttributeError super().speak() inside Dog → resumes the same search after Dog → Animal.speak
Core idea
Inheritance builds a search chain: a subclass adds or overrides names, and attribute lookup walks the MRO from the instance's class upward, so the first definition found wins. super() continues that search from wherever the current class sits, which is why cooperative methods stay correct even when several classes participate. The relationship is also a promise about substitutability: announce accepts a Dog because a Dog answers the same speak call an Animal does.
Base and derived classes
A base class (also called a superclass) is the class named in parentheses in a class statement; the derived class (subclass) extends it. The subclass inherits the base's attribute lookup: any name not defined on the subclass is searched on the base and then its bases in MRO order. This is a substitutability relationship, so a derived instance should work anywhere the base's interface is expected.
Method overriding
A subclass overrides a method by defining the same attribute name. Calls then resolve through the MRO, so the subclass behavior can replace or extend base behavior.
super()
super() performs lookup starting after the current class in the method resolution order. In multiple inheritance, cooperative methods should generally call super() consistently.
Cooperative inheritance
Cooperative inheritance designs methods so every participating class calls super() with compatible signatures. This lets the MRO compose multiple classes without hard-coded parent calls.
isinstance
isinstance(object, class_or_tuple) returns True when the object is an instance of that class or any subclass of it, following the MRO rather than comparing types exactly. It reads the actual type chain at runtime, so it also works with abstract base classes and tuples of candidate types. Prefer it over type(x) == C whenever subclasses might be involved.
issubclass
issubclass(class, class_or_tuple) returns True when the first argument is the second or a subclass of it, walking the MRO. It answers a question about classes, not objects, and raises TypeError if the first argument is not a class. Use it to validate registration logic or plugin checks where you reason about types themselves.
Walkthrough
class Dog(Animal)creates a subclass;Dog.__mro__is(Dog, Animal, object), and nothing is copied:Dog().speakfindsDog.speakfirst becauseDogis earlier in that order.announce(Dog())passes the instance to a function that only knows thespeakprotocol;animal.speak()callsDog.speak, so the print showswoofand the...fromAnimal.speaknever appears.- The two
speakmethods share one name, which is all overriding requires: the same call shape reaches the subclass version first. - Predict before running: what
announce(Dog())prints, whatannounce(Animal())prints, and what the output becomes if you deleteDog.speak.
Experiments to try
- Remove
Dog.speakand run again; note that lookup simply continues toAnimal, soannounce(Dog())prints...without any caller change. - Add
class Cat(Animal): passand compareCat().speak()withCat.speak; explain what the subclass inherited and where the method actually lives. - Print
Dog.__mro__and point to the order lookup would follow for a name that neither class defines. - Change
Dog.speaktoreturn super().speak() + " woof"and observe the combined output; explain wheresuper()started the search.
Common mistakes
- Treating inheritance as copying:
Dogdoes not contain a copy ofAnimal.speak, it only falls back to it through lookup, so editingAnimal.speakchanges whatDog().speak()returns wheneverDogdoes not override it. - Calling a method through the class as if it were bound:
Dog.speak()leavesselfunfilled and raisesTypeError, whiledog.speak()binds the instance automatically. - Using inheritance to borrow code when no substitutability holds, such as subclassing
Animalonly for a helper; the subclass then carries the whole base interface it never meant to promise. - Reading
super()as a fixed alias for the direct parent: it resolves to the next class after the current one in the MRO, which is what makes cooperative multiple inheritance work.
Practice: Easy
- Run the worked example, then print
Dog.__mro__andisinstance(Dog(), Animal). Record both outputs and explain what the MRO line promises about lookup. - Delete
Dog.speak, rerunannounce(Dog()), and explain why the output changes to...without touchingannounce. - Add
class Cat(Animal): passand compareCat().speak()withDog().speak(); say whichspeakeach call found and where it is defined.
Practice: Medium
- Override
speakinDogso it returnssuper().speak() + " woof"; verify the combined string and explain whatsuper()skipped past. - Add a shared
describe(self)toAnimalthat returnsf"{type(self).__name__} says {self.speak()}", run it on both classes, and explain how the overriding method is reached from the base method. - Check
issubclass(Dog, Animal),issubclass(Animal, Dog), andisinstance(Dog(), Animal); write one sentence for what each call actually answers.
Practice: Hard
- Design a three-level hierarchy
Shape→Polygon→Rectanglewhere each class adds one rule and every__init__cooperates withsuper().__init__(...). Sketch the MRO and a test that shows construction visits all three levels. - Build a failure lab: call
Animal.speak()with no instance, override a method with a different parameter list so an inherited caller breaks, and subclass only to borrow a helper where no subtype relationship exists. Record each error or design smell and the rule behind it. - Connect this lesson to the multiple inheritance lesson: construct a diamond where two subclasses both call
super().speak(), print the MRO, and explain how the chain decides whose method runs first and whetherAnimalruns once or twice.
Lesson checklist
- I can draw
Dog.__mro__from memory and point to where lookup starts. - I can explain why deleting
Dog.speakchanges the output without breakingannounce. - I can say what
super()continues from inside a method. - I can state the difference between
isinstance(dog, Animal)andissubclass(Dog, Animal).
Remember
Inheritance places the subclass earlier in the lookup chain, so overriding is just a name that resolves to the subclass's version before the base's. `super()` continues that same chain from the current class rather than jumping to a fixed parent, and `isinstance` and `issubclass` read the chain at runtime when a decision depends on the type relationship.
Interview angles
What is the main purpose of **Base and derived classes**?+
A base class (also called a superclass) is the class named in parentheses in a class statement; the derived class (subclass) extends it. The subclass inherits the base's attribute lookup: any name not defined on the subclass is searched on the base and then its bases in MRO order. This is a substitutability relationship, so a derived instance should work anywhere the base's interface is expected.
What should you pay attention to when using **Method overriding**?+
A subclass overrides a method by defining the same attribute name. Calls then resolve through the MRO, so the subclass behavior can replace or extend base behavior.
How does **super()** fit into this lesson?+
super() performs lookup starting after the current class in the method resolution order. In multiple inheritance, cooperative methods should generally call super() consistently.
Why does `Dog.speak()` raise `TypeError` while `dog.speak()` works?+
Methods are plain functions found through the class, so Dog.speak expects an instance as its first argument; calling it with none leaves self unfilled and raises TypeError. Accessing the same function through an instance binds the instance automatically, which is what dog.speak() uses.