Skip to content

    Inheritance & Dunder Methods

    Python · Intermediate

    Definition

    Inheritance lets a class reuse and extend another; dunder methods like __str__ and __len__ customize built-in behavior.

    Core to writing clean object-oriented Python.

    Diagram

    Animal↓ Dog↓ speak() overridden

    Flowchart

    Define base classSubclass with class B(A)Override methodsCall super()Add dunder methods

    Example: Override + __str__

    class Animal:
        def speak(self): return '...'
    class Dog(Animal):
        def speak(self): return 'Woof'
        def __str__(self): return 'Dog'
    d = Dog()
    print(d, d.speak())

    Output: Dog Woof

    Key points

    • super() calls the parent
    • __eq__ and __hash__ go together

    Interview questions

    What is MRO?

    Method Resolution Order — the order Python searches classes for a method.

    More Python topics