Academic Block

Python InheritanceGet Certified

What Is Inheritance?

Inheritance lets one class reuse and extend the code of another class. Think of how a pickup truck and a sedan are both kinds of vehicle: they share wheels, an engine, and a way to start, but each also has features of its own. In Python you write the shared parts once in a parent class, and then create child classes that automatically receive everything the parent has. A child class can add new attributes and methods, or change the behavior it inherited. This saves you from copying code, keeps related classes organized, and makes a program easier to change, because a fix in the parent reaches every child at once.

  • Parent class: the class that is inherited from. It is also called the base class or superclass.
  • Child class: the class that inherits. It is also called the derived class or subclass.
  • “Is-a” relationship: a Car is a Vehicle, and a Student is a Person.
  • Reuse: a child gets all the attributes and methods of its parent without rewriting them.
  • Overriding: a child can replace a method of its parent with its own version.
  • super(): a way for the child to call the parent’s code.

Creating a Child Class

To create a child class, write the name of the parent class in parentheses after the name of the new class: class Car(Vehicle):. That single change gives Car every attribute and method that Vehicle defines. If the child needs nothing extra yet, its body can be just pass, and it still works as a complete class. When you create an object from the child class, Python looks for each method in the child first, and then in the parent, so the parent’s methods are found automatically. If the child has no __init__ of its own, the parent’s __init__ is used to build the object.

Try It: A Child Class That Inherits Everything

Click Test My Code. Then add a second child class named Truck(Vehicle) with pass and create a truck object.

What this code does: It defines a Vehicle class with an initializer and two methods, and an empty Car class that inherits from it. It creates a car, calls the inherited methods, and uses isinstance() and issubclass() to confirm the relationship between the two classes.
class Vehicle:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def describe(self):
        return f"{self.make} {self.model}"

    def start(self):
        return f"The {self.model} is starting"

class Car(Vehicle):
    pass

car = Car("Ford", "Mustang")
print(car.describe())
print(car.start())
print(isinstance(car, Car), isinstance(car, Vehicle))
print(issubclass(Car, Vehicle))

Adding New Attributes with super().__init__()

A child class usually needs more than its parent has, for example a student has a school and a grade point average on top of a name and a city. When you write an __init__ in the child class, it replaces the parent’s __init__, so the parent’s attributes would not be created unless you ask for them. The built-in super() function solves this: it gives you access to the parent class, so super().__init__(...) runs the parent’s initializer for you. The usual pattern is to call it first, and then to set the attributes that belong only to the child.

Try It: A Student Is a Person

Click Test My Code. Comment out the super().__init__ line, run it again, and read the error.

What this code does: It defines a Person class with a name, a city, and an introduce() method. The Student child class adds a school and a grade point average, calls the parent initializer with super(), and adds a study() method. The program creates one student and uses methods and attributes from both classes.
class Person:
    def __init__(self, name, city):
        self.name = name
        self.city = city

    def introduce(self):
        return f"Hi, I'm {self.name} from {self.city}."

class Student(Person):
    def __init__(self, name, city, school, gpa):
        super().__init__(name, city)
        self.school = school
        self.gpa = gpa

    def study(self):
        return f"{self.name} is studying at {self.school}."

emma = Student("Emma Davis", "Chicago", "Northwestern University", 3.9)
print(emma.introduce())
print(emma.study())
print(emma.gpa, emma.city)

Overriding Methods and Extending Them with super()

Sometimes a child class needs to behave differently from its parent. To change an inherited method, you define a method with the same name in the child class. This is called overriding, and Python always chooses the child’s version for objects of the child class. The parent’s version is not lost, because inside the child’s method you can call super().method_name() to run the parent’s code and then build on its result. This lets a child extend a behavior instead of rewriting it from scratch.

Try It: Employees and Managers

Click Test My Code. Change the manager’s bonus to 0 and check that both people are paid the same way.

What this code does: It defines an Employee class whose annual_pay() returns the salary. A Manager child class adds a bonus and overrides annual_pay() to add the bonus to the pay calculated by the parent. A loop prints the pay of one employee and one manager.
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def annual_pay(self):
        return self.salary

class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)
        self.bonus = bonus

    def annual_pay(self):
        return super().annual_pay() + self.bonus

staff = [Employee("Tyler Brooks", 52000), Manager("Jennifer Ramirez", 78000, 12000)]
for person in staff:
    print(f"{person.name}: ${person.annual_pay():,}")

Checking Relationships: isinstance(), issubclass(), and the MRO

Python gives you several tools to ask how objects and classes are related. The function isinstance(obj, Class) is true when the object belongs to the class or to any of its parents, which is exactly what the “is-a” idea means. The function issubclass(A, B) asks the same question about two classes. By contrast, type(obj) returns only the exact class of the object, so comparing it with == ignores inheritance. Every class also keeps a record of its ancestors: __bases__ lists its direct parents, and __mro__, the method resolution order, lists every class in the order in which Python searches for a method.

  • isinstance(obj, Class) is true for the class of the object and for all of its ancestors.
  • issubclass(Child, Parent) is true when the child inherits from the parent, directly or indirectly.
  • type(obj) == Class is true only for the exact class, so it is stricter than isinstance().
  • Class.__mro__ shows the search order, and the last class is always object.
  • Every class in Python inherits from the built-in class object, even when you do not write it.

Try It: A Family Tree of Classes

Click Test My Code. Predict each line before you read the output, especially the one that compares exact types.

What this code does: It builds a chain of three classes, Animal, Dog, and Puppy, and creates a puppy. It tests the puppy with isinstance(), tests the classes with issubclass(), shows the exact type, compares exact types, and prints the method resolution order and the direct parent of Dog.
class Animal:
    pass

class Dog(Animal):
    pass

class Puppy(Dog):
    pass

rex = Puppy()
print(isinstance(rex, Puppy), isinstance(rex, Dog), isinstance(rex, Animal))
print(issubclass(Puppy, Animal), issubclass(Animal, Puppy))
print(type(rex).__name__)
print(type(rex) == Dog)
print([cls.__name__ for cls in Puppy.__mro__])
print(Dog.__bases__[0].__name__)

Multi-Level Inheritance

Inheritance can go several levels deep: a class can inherit from a class that itself inherits from another class, forming a chain. An electric car, for example, is a car, and a car is a vehicle, so an ElectricCar receives the code of both Car and Vehicle. Each level adds something new, and each initializer calls super().__init__() to pass the shared values up the chain. When you create an object of the lowest class, the initializers run from the bottom up to the top, and they finish in the opposite order, so the parent’s work is always done first.

Try It: A Chain of Initializers

Click Test My Code. Watch the order of the three messages carefully, because it shows how the initializers call each other.

What this code does: It defines three classes in a chain: Vehicle, Car, and ElectricCar. Each initializer prints a message and passes its shared values up with super(). Creating one electric car shows the order in which the messages appear, and the final line proves that the object has the attributes of all three classes.
class Vehicle:
    def __init__(self, brand):
        self.brand = brand
        print("Vehicle created")

class Car(Vehicle):
    def __init__(self, brand, doors):
        super().__init__(brand)
        self.doors = doors
        print("Car created")

class ElectricCar(Car):
    def __init__(self, brand, doors, range_miles):
        super().__init__(brand, doors)
        self.range_miles = range_miles
        print("ElectricCar created")

tesla = ElectricCar("Tesla", 4, 358)
print(tesla.brand, tesla.doors, tesla.range_miles)

Multiple Inheritance and the MRO

Python also allows a class to have more than one parent: class Triathlete(Swimmer, Runner):. The child receives the methods of every parent, which is useful when a class combines separate abilities. If two parents define a method with the same name, Python needs a rule to choose, and the rule is the method resolution order. It searches the child first, and then the parents from left to right in the order they are written, and each class is searched only once. Multiple inheritance is powerful but can make code hard to follow, so use it sparingly and keep the parent classes small and independent.

Try It: Combining Two Parents

Click Test My Code. Swap the order of the parents to (Runner, Swimmer) and see how the first result changes.

What this code does: It defines a Swimmer and a Runner. Both have a move() method, and the runner also has sprint(). The Triathlete class inherits from both. The program shows which move() wins, calls the method that only one parent has, and prints the order in which Python searches the classes.
class Swimmer:
    def move(self):
        return "swims"

class Runner:
    def move(self):
        return "runs"

    def sprint(self):
        return "sprints"

class Triathlete(Swimmer, Runner):
    pass

athlete = Triathlete()
print(athlete.move())
print(athlete.sprint())
print([cls.__name__ for cls in Triathlete.__mro__])

Inheritance vs Composition

Inheritance is not always the right tool. It fits an “is-a” relationship, such as a Car that is a Vehicle. When one object merely has another object, as a truck has an engine, the better design is composition: the truck stores an Engine object in an attribute and calls its methods. A truck is not a kind of engine, so inheriting from Engine would be wrong and confusing. A helpful test is to say the sentence aloud: “a truck is an engine” sounds odd, while “a truck has an engine” sounds right, so composition is the better choice.

  • Inheritance models “is-a”: a Student is a Person.
  • Composition models “has-a”: a Truck has an Engine, and a School has many Student objects.
  • Composition is more flexible, because the parts can be replaced without changing the class hierarchy.
  • Prefer shallow hierarchies, because deep chains of parents are hard to understand and change.

Try It: A Truck Has an Engine

Click Test My Code. Change the horsepower to 300 and see where the value is used.

What this code does: It defines an Engine class and a Truck class that stores an engine object inside itself instead of inheriting from it. The truck’s start() method asks its engine to start, and the last line shows that a truck is not an instance of Engine.
class Engine:
    def __init__(self, horsepower):
        self.horsepower = horsepower

    def start(self):
        return "Engine roars to life"

class Truck:
    def __init__(self, model, horsepower):
        self.model = model
        self.engine = Engine(horsepower)

    def start(self):
        return f"{self.model}: {self.engine.start()}"

pickup = Truck("Ranger", 400)
print(pickup.start())
print(pickup.engine.horsepower)
print(isinstance(pickup, Engine))

Base Classes That Require Overriding

Sometimes a parent class describes what its children must be able to do, without knowing how each child does it. A Shape class, for instance, can promise an area() method, but the formula depends on whether the shape is a rectangle or a circle. A common way to express this promise is to make the parent’s method raise NotImplementedError, which tells every child class: “you must replace this method”. Children that override the method work normally, and a child that forgets it fails with a clear message. Python’s abc module offers an even stricter tool, abstract base classes, which you can explore later.

Try It: A Shape Family

Click Test My Code. Add an area() method to Circle that returns 3.14 * self.radius ** 2 and watch the last line change.

What this code does: It defines a Shape base class whose area() raises NotImplementedError. Rectangle overrides it, Square inherits from Rectangle and passes its side twice to the parent initializer, and Circle forgets to override it. A loop shows what happens for each one.
class Shape:
    def area(self):
        raise NotImplementedError("Subclasses must implement area()")

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

class Square(Rectangle):
    def __init__(self, side):
        super().__init__(side, side)

for shape in [Rectangle(3, 4), Square(5), Circle(2)]:
    try:
        print(type(shape).__name__, shape.area())
    except NotImplementedError as error:
        print(type(shape).__name__, "->", error)
Tip: When you design a family of classes, put the attributes and methods that every child needs in the parent, and keep what is special in the children. Ask yourself whether the sentence “a child is a parent” makes sense. If it does not, use composition instead. Keep the hierarchy shallow: two or three levels are usually plenty.

Using Inheritance with User Input

Inheritance combines well with user input, because a program can read a few answers and then decide which class to create. Classes are ordinary objects in Python, so you can store them in a dictionary and look them up by name, which avoids a long chain of if statements. The object that you create then behaves according to its class, but you can use it in the same way as any other object of the family. Remember that input() returns text, so convert numbers with int() or float() before you pass them to a class.

Try It: Choosing a Pet Class

The Program Input box is already filled with three lines: Buddy, Dog, and 3. Click Run Code straight away, then try cat, and finally a kind that is not in the dictionary, such as parrot.

What this code does: It defines a Pet base class and two children, Dog and Cat, that override the sound() method. A dictionary maps the words dog and cat to their classes. The program reads a name, a kind, and an age, picks the matching class with get(), falling back to Pet, and creates and describes the pet.
class Pet:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sound(self):
        return "..."

class Dog(Pet):
    def sound(self):
        return "Woof"

class Cat(Pet):
    def sound(self):
        return "Meow"

kinds = {"dog": Dog, "cat": Cat}
name = input("Pet name: ")
kind = input("Dog or cat? ").strip().lower()
age = int(input("Age: "))
pet = kinds.get(kind, Pet)(name, age)
print(f"{pet.name} ({type(pet).__name__}), age {pet.age}, says {pet.sound()}")
print(isinstance(pet, Pet))

Try It: A Savings Account

The Program Input box is filled with three lines: Michael Johnson, 1000, and 5. Click Run Code, then try other balances and interest rates.

What this code does: It defines an Account class with a deposit() method, and a SavingsAccount child class that adds an interest rate and an add_interest() method. The method reuses the inherited deposit(). The program reads the details, creates a savings account, deposits $250, adds interest, and prints the balance.
class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

class SavingsAccount(Account):
    def __init__(self, owner, balance, rate):
        super().__init__(owner, balance)
        self.rate = rate

    def add_interest(self):
        self.deposit(self.balance * self.rate / 100)

owner = input("Account owner: ")
balance = float(input("Starting balance: "))
rate = float(input("Interest rate (%): "))

account = SavingsAccount(owner, balance, rate)
account.deposit(250)
account.add_interest()
print(f"{account.owner}'s balance: ${account.balance:,.2f}")

Common Mistakes with Inheritance

Inheritance is easy to start with and surprisingly easy to misuse. Most problems come from forgetting how the parent and the child cooperate, or from choosing inheritance when a simpler design would work better. Some mistakes raise a clear error, such as a missing attribute, while others silently do the wrong thing, such as a method that was meant to override but has a slightly different name. Check the list below when an object does not behave as you expect.

  • Forgetting super().__init__(): when a child defines its own __init__, the parent’s attributes are not created. Later you get an AttributeError.
  • Wrong arguments to super().__init__(): passing too few or too many values raises a TypeError. Match the parent’s parameters.
  • A misspelled method name: a child method called anual_pay() does not override annual_pay(). It just creates a new method, and the parent’s version still runs.
  • Forgetting the parent in the class line: class Car: creates an unrelated class. Write class Car(Vehicle):.
  • Using inheritance for “has-a”: a truck is not an engine. Store the engine in an attribute instead.
  • Deep or tangled hierarchies: long chains and complicated multiple inheritance are hard to follow. Keep the tree shallow.
  • Comparing with type(obj) == Class: this ignores subclasses. Use isinstance() in most cases.
  • Changing the meaning of an inherited method: a child should accept the same kinds of arguments and return the same kind of result as the parent, so that it can be used wherever the parent is expected.

Key Takeaways

Inheritance is one of the main tools of object-oriented programming, and with it you can build families of related classes without repeating code. The points below summarize the essentials, and they prepare you for the next lesson on polymorphism and encapsulation, where you will see how objects of different classes can be used in the same way. Keep this list in mind whenever you design a new class that resembles an existing one.

  • A child class inherits all the attributes and methods of its parent: class Child(Parent):.
  • Use super().__init__(...) in the child’s initializer to run the parent’s initializer, and then add the child’s own attributes.
  • A method with the same name in the child overrides the parent’s method, and super().method() lets the child extend it.
  • isinstance() and issubclass() test “is-a” relationships, and __mro__ shows the order in which Python searches for methods.
  • Inheritance can have several levels, and a class can have several parents, but a shallow and simple hierarchy is easier to understand.
  • Use inheritance for “is-a” and composition for “has-a”.
  • A base method that raises NotImplementedError tells every child that it must provide its own version.

Frequently Asked Questions

The questions below are the ones that students ask most often when they first learn about inheritance in Python. Each answer is short and practical, and each idea is shown in one of the examples above. If you are still unsure, experiment: create a small parent class, derive a child from it, and change one thing at a time to see how the behavior changes.

What is inheritance in Python?

Inheritance is a feature of object-oriented programming in which a child class receives the attributes and methods of a parent class. The child can reuse that code, add new attributes and methods, and override the behavior that it inherited.

How do I make a class inherit from another class in Python?

Write the name of the parent class in parentheses after the name of the child class, for example class Car(Vehicle):. The Car class then has all the attributes and methods of Vehicle.

What does super() do in Python?

The super() function gives a child class access to its parent class. It is most often used as super().__init__(…) to run the parent’s initializer, and as super().method_name() to call the parent’s version of a method that the child has overridden.

What is method overriding in Python?

Method overriding means that a child class defines a method with the same name as a method of its parent. Python then uses the child’s version for objects of the child class. The child can still call the parent’s version with super().

What is the difference between isinstance() and type() in Python?

The isinstance(obj, Class) function is true when the object belongs to the class or to any of its parent classes. Comparing type(obj) == Class is true only for the exact class. For this reason isinstance() is usually the better choice when inheritance is involved.

Does Python support multiple inheritance?

Yes. A class can list several parents, as in class Triathlete(Swimmer, Runner):. Python looks for a method in the child first and then in the parents from left to right, following the method resolution order, which you can see in Class.__mro__.

What is the method resolution order (MRO) in Python?

The method resolution order is the sequence of classes that Python searches when you call a method or read an attribute of an object. It starts with the object’s own class, continues through the parent classes, and ends with the built-in class object. You can print it with Class.__mro__.

When should I use composition instead of inheritance in Python?

Use inheritance for an “is-a” relationship, such as a Student that is a Person. Use composition for a “has-a” relationship, such as a Truck that has an Engine, by storing the other object in an attribute. Composition is more flexible and avoids deep class hierarchies.

Ready for the next step?Learn how different classes can respond to the same method in their own way.
Next: Polymorphism & Encapsulation →