LearnPy Hub
IntermediateIntermediateLesson 19 of 32

Inheritance & Special Methods

Watch the ideaA child class reuses its parent
class Animal:
    def speak(self): return "..."
    def eat(self): return "nom"

class Dog(Animal):
    def speak(self): return "woof"
Animal
speak()'...'
eat()'nom'
Dog(Animal)
speak()'woof'
eat()from Animal

Dog(Animal) means a Dog gets everything an Animal has, and can add or change things.

1Level 1 · BasicsBasics

Often one kind of thing is a special version of another: a student is a person, a savings account is a bank account. Inheritance lets a new class reuse everything from an existing class and add or change only what's different. This lesson also covers special methods, which make your objects work with print(), len(), + and ==.

Inheritance

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

class Dog(Animal):           # Dog inherits from Animal
    def speak(self):         # override: replace the parent's version
        return "Woof!"

Dog(Animal) means Dog is a child (subclass) of Animal, the parent. Dog gets __init__ and name for free, and replaces speak with its own version. This is called overriding.

super(): reuse the parent's code

When the child needs extra setup, call the parent's version with super() and then add to it:

class Student(Person):
    def __init__(self, name, age, dept):
        super().__init__(name, age)   # let Person set name and age
        self.dept = dept              # then add the new part

Polymorphism

Different classes can have methods with the same name. A loop can call animal.speak() on a Dog, a Cat or a Cow without caring which one it is, and each answers in its own way. isinstance(obj, Animal) checks whether an object is an Animal (or a child of one).

Special ("dunder") methods

Methods with double underscores on both sides let your objects work with Python's built-in syntax:

MethodUsed by
__str__(self)print(obj) and str(obj): a friendly description
__repr__(self)the developer view, shown in lists and the console
__len__(self)len(obj)
__eq__(self, other)obj == other
__add__(self, other)obj + other
__lt__(self, other)obj < other, and so sorted()

Dataclasses: less typing

For classes that mainly hold data, @dataclass writes __init__, __repr__ and __eq__ for you, based on the fields you list.

Key points: class Child(Parent) inherits; override a method by redefining it; super() calls the parent's version; dunder methods hook into print, len, +, == and sorting; @dataclass saves boilerplate.

See it in actionThe child class overrides a method

Dog gets __init__ from Animal but uses its own speak().

Step-by-step

Try it yourselfExample 1: Inheritance and overriding

Each animal shares __init__ from Animal but speaks in its own way.

example_1.py
Output appears here
Fill in the blanks

A Cat is an Animal

Fill the blanks so Cat inherits from Animal and overrides sound(), printing Meow.

blanks.py
class Animal:
    def sound(self):
        return "..."

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

print(Cat().sound())
Your turn

Shapes with area

Make a base class Shape with area() returning 0, and subclasses Square(side) and Circle(r). Print the area of a Square of side 3 and of a Circle of radius 1 rounded to 2 places: 9 3.14.

my_code.py

Example 2: super() for extra setup

Student reuses Person's setup, then adds its own attribute and method.

example_2.py
Output appears here
Fix the bug

Forgot to call super()

Student should keep the name set up by Person and print Mim 8, but it crashes. Fix Student.__init__.

buggy.py

Example 3: Special methods

__str__, __add__, __eq__ and __len__ make Vector objects feel built in.

example_3.py
Output appears here
Fill in the blanks

A nice printout

Fill the blank so printing a Book shows Dune by Herbert.

blanks.py
class Book:
    def __init__(self, title, author):
        self.title, self.author = title, author

    def (self):
        return f"{self.title} by {self.author}"

print(Book("Dune", "Herbert"))

Example 4: Dataclasses and sorting

@dataclass writes __init__ and __repr__; order=True adds comparisons so sorted() works.

example_4.py
Output appears here
Your turn

Sort with __lt__

Give Card a __lt__ method that compares by value, so sorted() works. Print the sorted values of cards 7, 2, 9: [2, 7, 9].

my_code.py

2Level 2 · IntermediateAbstract classes and more special methods

Abstract base classes

from abc import ABC, abstractmethod. A class with an @abstractmethod can't be created directly; every child must implement the method. This is how you define a "shape contract": every shape has an area().

Operator overloading

__add__ makes a + b work, __lt__ makes sorting work, __len__ answers len(), __getitem__ allows obj[i], and __contains__ answers in.

isinstance and duck typing

isinstance(x, Shape) checks the family tree. But Python usually prefers duck typing: if an object has the method you need, just call it.

See it in actionWhich method runs?

Watch Python look up speak() on each object's own class first.

Step-by-step

Example 5: Shapes with an abstract base class

Shape() can't be created, and every shape sorts by area thanks to __lt__.

example_5.py
Output appears here

Example 6: A playlist that acts like a list

len, indexing, in and + all work because of special methods.

example_6.py
Output appears here

3Level 3 · AdvancedMultiple inheritance, MRO and mixins

Method resolution order

With several parents, Python searches classes in a fixed order called the MRO (Class.__mro__). super() calls the next class in the MRO, not simply "the parent", which is how cooperative classes all get a turn.

Mixins

A mixin is a small class that adds one ability (logging, JSON export, comparison) and is meant to be combined with others: class Student(JsonMixin, Person).

Dataclasses go further

@dataclass(order=True, frozen=True) generates comparison methods and makes objects read-only; field(default_factory=list) avoids the shared-default trap.

When not to inherit

If the child doesn't truly pass every test the parent would ("a Square is a Rectangle" breaks when you change width alone), use composition.

Example 7: super() follows the MRO

Each class adds its part and passes on to the next one in the MRO.

example_7.py
Output appears here

Example 8: A mixin and a frozen, ordered dataclass

to_json comes from the mixin; sorting and read-only come from the dataclass.

example_8.py
Output appears here
Good practiceUse inheritance for a real "is a" relationship (a Dog is an Animal). If one thing merely has another, like a Car that has an Engine, store it as an attribute instead. That's called composition, and it's usually simpler.
Exercise · predict the output

What does this print?

class A:
    def hi(self):
        return "A"
class B(A):
    def hi(self):
        return "B" + super().hi()
print(B().hi())
Quick quiz · 5 questions
1. In class Car(Vehicle), which class is the parent?
2. What does super().__init__(name) do inside a child class?
3. Which special method controls what print(obj) shows?
4. What is overriding?
5. Which special method makes obj1 + obj2 work?
Ready to practice inheritance & special methods?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Inheritance & Special Methods · LearnPy Hub