Hiprup

How does inheritance work in Python?

Inheritance in Python lets a class derive attributes and behaviour from one or more parent (base) classes. The child class is-a specialized form of the parent, can add new members, and can override or extend existing ones.

Basic syntax:

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

class Dog(Animal):
    def speak(self): return "woof"    # override

class Puppy(Dog):
    def speak(self):                 # extend via super()
        return super().speak() + "!"

Multiple inheritance — Python supports it; a class can list several bases. Attribute lookup follows the MRO (Method Resolution Order), computed by the C3 linearization algorithm, viewable via Cls.__mro__ or help(Cls). The MRO gives a deterministic, left-to-right, depth-first search that honors every parent’s ordering.

# Single inheritance
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return f'{self.name} makes a sound'

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # Call parent constructor
        self.breed = breed
    def speak(self):            # Override parent method
        return f'{self.name} barks'

dog = Dog('Rex', 'Labrador')
print(dog.speak())  # 'Rex barks'
print(isinstance(dog, Animal))  # True

# Multiple inheritance with MRO
class Flyable:
    def move(self):
        return 'flying'

class Swimmable:
    def move(self):
        return 'swimming'

class Duck(Flyable, Swimmable):  # Flyable first in MRO
    pass

duck = Duck()
print(duck.move())  # 'flying' — Flyable is first in MRO
print(Duck.__mro__)
# (Duck, Flyable, Swimmable, object)

# Diamond inheritance with super()
class A:
    def __init__(self):
        print('A')
        super().__init__()

class B(A):
    def __init__(self):
        print('B')
        super().__init__()

class C(A):
    def __init__(self):
        print('C')
        super().__init__()

class D(B, C):  # Diamond
    def __init__(self):
        print('D')
        super().__init__()

D()  # Prints: D, B, C, A — each called once (MRO)

Dog inherits from Animal and overrides speak(). super().init() calls the parent's constructor. Duck inherits from Flyable and Swimmable — MRO determines Flyable.move() wins.

The diamond example shows cooperative multiple inheritance: super() follows MRO (D -> B -> C -> A), calling each init exactly once.

MRO (Method Resolution Order) is the key concept for multiple inheritance. Know that super() follows MRO, not just the immediate parent.

The diamond problem resolution (each class called once via C3 linearization) is commonly asked. Show mro to inspect the order.

How does inheritance work in Python? | Hiprup