Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 08

Inheritance — Reuse a Base Class in a Derived Class

Reuse Python class features with inheritance, create the object from the derived class, and recognize the five inheritance patterns.

Intermediate25 min
Inheritance hero Module 17 Lesson 8 base and derived class

Inheritance copies nothing by hand. The derived class receives the data members, methods, and constructors of the base class and can add its own.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • Why inheritance exists
  • Base class and derived class
  • The syntax class Child(Parent)
  • The five patterns, with one working single-inheritance example

The picture

Five ways classes can be connected

The base class is also called the super or parent. The derived class is the sub or child. The child obtains the parent's features. You do not paste the parent source into the child, and you do not allocate a second copy of those methods for the child to own physically. The child uses them.

Advantages you can feel in a small program:

  • Less time, because the parent already has the method
  • Less duplicated code
  • A child object can do the parent's job plus its own
text
class GuideBadge(Badge):
    ...

Badge is the base. GuideBadge is the derived class. Several bases can be listed in the parentheses: class Child(First, Second).

Every Python class has an implicit base called object. That is why a class you write can still be created and collected even when you do not name a parent.

When classes form a chain, create the object from the bottom-most derived class. That object can use what it defined and what it inherited.

Pattern Shape
Single One parent, one child
Multi-level Parent, child, grandchild
Hierarchical One parent, several children
Multiple Several parents, one child
Hybrid A combination of the patterns above

The example is single inheritance. The other four are the same idea with more classes in the diagram.

Example

python
class Badge:
    def __init__(self, m):
        self.label = m

    def introduce(self):
        return self.label

class GuideBadge(Badge):
    def role(self):
        return "guide"

guide = GuideBadge("Avery Lane")
print(guide.introduce())
print(guide.role())

introduce was written on Badge. GuideBadge did not copy it. The object is a GuideBadge, the bottom class, so it can introduce itself and report its role. The playground prints both lines.

Key takeaways

  • Inheritance reuses a base class inside a derived class

  • Syntax: class Child(Parent)

  • Create the object from the most derived class

  • Every class implicitly inherits object

  • The five patterns are single, multi-level, hierarchical, multiple, and hybrid

  • Next: Polymorphism — the same method name, a new body

  • Previous: Encapsulation and Abstraction

Loading playground…

Check your understanding

Inheritance quiz

Inheritance is used to:

1 / 10