Inheritance

A class can inherit and extend another class.

Syntaxclass Child(Parent): ...

Inheritance lets a new class reuse the attributes and methods of an existing one. The new class is the child (subclass); the original is the parent (superclass).

Overriding and super()

  • A child can override a method by redefining it.
  • super() calls the parent's version, often used inside __init__.

Example

Example · python
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return 'some sound'

class Cat(Animal):
    def speak(self):
        return f'{self.name} says Meow'

c = Cat('Milo')
print(c.speak())

# Output:
# Milo says Meow

When to use it

  • An Animal base class defines eat() and sleep(); Dog and Cat subclasses add speak() with their own sound.
  • A base HTTPHandler processes common headers; GetHandler and PostHandler extend it for method-specific logic.
  • A Shape base class has an abstract area(); Circle and Square override it with their own formulas.

More examples

Basic single inheritance

Dog and Cat inherit name from Animal and each override speak() with their own return value.

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

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

class Dog(Animal):
    def speak(self):
        return 'Woof!'

class Cat(Animal):
    def speak(self):
        return 'Meow!'

for animal in [Dog('Rex'), Cat('Whiskers')]:
    print(animal.name, '->', animal.speak())
# Rex -> Woof!
# Whiskers -> Meow!

Call parent method with super()

Uses super().__init__() to reuse the parent's initialisation before adding the child's own attribute.

Example · python
class Vehicle:
    def __init__(self, make, speed):
        self.make = make
        self.speed = speed

class ElectricCar(Vehicle):
    def __init__(self, make, speed, range_km):
        super().__init__(make, speed)  # call parent __init__
        self.range_km = range_km

tesla = ElectricCar('Tesla', 200, 500)
print(tesla.make, tesla.range_km)   # Tesla 500

isinstance() checks with inheritance

Shows that isinstance() respects the inheritance chain while type() checks the exact class.

Example · python
class Shape:
    pass

class Circle(Shape):
    pass

c = Circle()
print(isinstance(c, Circle))  # True
print(isinstance(c, Shape))   # True (Circle IS-A Shape)
print(type(c) is Shape)       # False

Discussion

  • Be the first to comment on this lesson.