Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Inheritance

Inheritance lets a new class take over everything from an existing class and then add or change what it needs. The existing class is the parent (or base class), and the new one is the child (or subclass). A Car and a Bike are both vehicles: they share a brand, a speed and a way to describe themselves, and each adds its own details. Inheritance avoids writing the shared parts twice.

A parent and a child class

The parent goes in brackets after the child's name. The child inherits all the parent's attributes and methods:

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

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

    def describe(self):
        return f"{self.name} says {self.speak()}"

class Dog(Animal):
    def speak(self):
        return "Woof"

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

for pet in [Dog("Rex"), Cat("Tom"), Animal("Fish")]:
    print(pet.describe())
Output
Rex says Woof
Tom says Meow
Fish says ...

Dog and Cat override speak with their own version. describe is written only once, in Animal, but it calls whichever speak belongs to the actual object.

Extending the constructor with super()

When a child needs extra attributes, it defines its own __init__ and calls the parent's constructor with super(), so the shared setup is not repeated:

class Vehicle:
    def __init__(self, brand, wheels):
        self.brand = brand
        self.wheels = wheels

    def info(self):
        return f"{self.brand} with {self.wheels} wheels"

class Car(Vehicle):
    def __init__(self, brand, seats):
        super().__init__(brand, 4)
        self.seats = seats

    def info(self):
        return super().info() + f" and {self.seats} seats"

print(Vehicle("Hero", 2).info())
print(Car("Tata", 5).info())
Output
Hero with 2 wheels
Tata with 4 wheels and 5 seats

super().info() runs the parent's version of the method, and the child adds to its result. This is the usual way to extend behaviour rather than replace it completely.

Checking types

isinstance(obj, Class) is true for objects of the class and of its children; issubclass checks the relation between two classes:

class Animal: pass
class Dog(Animal): pass

rex = Dog()
print(isinstance(rex, Dog), isinstance(rex, Animal), isinstance(rex, str))
print(issubclass(Dog, Animal), issubclass(Animal, Dog))
print(Dog.__bases__[0].__name__)
Output
True True False
True False
Animal

Every class has a parent

A class without a parent in brackets inherits from object, Python's root class, which provides basic methods such as __str__ and __eq__. A class can even have several parents, called multiple inheritance, but use that sparingly: deep or tangled family trees make code hard to follow. Prefer inheritance when the child truly is a kind of the parent.

Practice exercises

  1. Write a class Shape with a method area returning 0, and children Square and Circle that override it.
  2. Print the area of a list of mixed shapes in one loop.
  3. Write Employee with a name and salary, and Manager(Employee) that adds a team list and uses super().__init__.
  4. Check with isinstance which of your objects are shapes.