Course outline · 0% complete

0/27 lessons0%

Course overview →

Inheritance

lesson 3-4 · ~12 min · 10/27

Building on an existing class

Sometimes a new class is an existing class plus a twist. Inheritance expresses that: the child class gets every method and attribute of the parent for free, then adds or overrides what differs.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"

class Dog(Animal):
    def speak(self):
        return f"{self.name} says woof"

Dog(Animal) reads as "Dog is an Animal". Dog did not define __init__, so the parent's runs. It did define speak, so its version overrides the parent's.

super(): extend instead of replace

Often the child wants to add to the parent's __init__ rather than replace it. super() calls the parent's version so you do not repeat its work:

class Puppy(Dog):
    def __init__(self, name, months):
        super().__init__(name)   # parent stores name
        self.months = months     # child adds its own data

When you call a method, Python looks for it on the object's own class first, then walks up the chain of parents and uses the first match. That lookup path is why overriding works.

Use inheritance for genuine is-a relationships. If the honest sentence is "has a" (a Car has an Engine), store the object as an attribute instead. Overusing inheritance is a classic beginner-to-intermediate mistake.

You will consume inheritance constantly even if you rarely write deep hierarchies of your own: custom exceptions subclass Exception (unit 8), Counter subclasses dict (unit 6), and every web framework hands you base classes to extend.

Code exercise · python

Run this program. Dog overrides speak, Cat inherits everything unchanged, and Puppy extends __init__ with super().

Code exercise · python

Your turn. Create a Manager class that inherits from Employee. Its __init__ takes name, salary, and team_size, and must call super().__init__ for the first two. Override describe to add the team size as shown.

Quiz

Class C(B) and class B(A). If c = C() and only A defines greet, what happens on c.greet()?

Quiz

A Car class needs an Engine. Should Car inherit from Engine?