Skip to content
BENIBIX Learn

Inheritance

Development🧭 Programming ParadigmsObject-Oriented Programming

Also known as Subclass, Child Class, Parent Class

A new class that gets all of an old class's parts, then adds its own.

Think of it like

Think of it like a kid with a parent's eyes. The kid learns new tricks too.

Example

Jack has an Animal class with a breathe method. His Cat class inherits it, so every cat can breathe without new code.

Why it matters

It is the most common way to share code between related classes in OOP.

Definition

Inheritance lets a new class take on all the data and methods of a class that exists. Then it can add or change some. The old class is called the parent, and the new one is the child. A Cat class can get breathe from an Animal class and add its own meow. It saves writing the same code twice. Long chains of it, though, get hard to follow.

Example code

python
class Animal:
    def breathe(self):
        return "in, out"

class Cat(Animal):
    pass

print(Cat().breathe())  # in, out
Cat writes no code of its own, yet it can breathe.

Common mistake

Inheriting just to reuse one method. If a Cat is not truly a kind of the parent, pass the helper in instead.

Key takeaways

  1. 1
    Parent and child. The child gets it all.
  2. 2
    Add or change. The child can do more.
  3. 3
    Keep chains short. Deep ones get confusing.

Compare