L2 · Working engineerObject-oriented Python~4 min · 4 tests#72

Inheritance in Python: Animal and Dog

Use Python inheritance so Dog reuses Animal's constructor and methods while adding its own speak(). Learn isinstance and method lookup, tested live.

The problem

  • Animal(name) stores name and has describe() returning "<name> is an animal".
  • Dog inherits from Animal (no __init__ of its own) and adds speak() returning "Dog barks".

Examples

  1. Example 1

    Input

    Dog("Rex").speak()

    Expected output

    'Dog barks'
  2. Example 2

    Input

    Dog("Rex").describe()

    Expected output

    'Rex is an animal'

+ 2 hidden tests on Submit.

Edge cases to ask about

  • Inherited init
  • isinstance with parent class

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · Dog
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    class Dog(Animal)O(1)O(1)Attribute lookup walks the MRO: Dog → Animal → object.
    Walkthrough of the optimal approach (try it yourself first)

    class Dog(Animal) makes Dog a subclass: it gets __init__ and describe from Animal and adds speak. Python finds attributes by walking the MRO (Dog.__mro__).

    Inheritance models an is-a relationship. If you only need to reuse behaviour, composition (question 80) is usually the better choice.

    Complexity: O(1) time, O(1) space. Method lookup follows a fixed-length chain of classes.

    Reveal the reference solution
    class Animal:
        def __init__(self, name):
            self.name = name
    
        def describe(self):
            return f"{self.name} is an animal"
    
    
    class Dog(Animal):
        def speak(self):
            return "Dog barks"

    Follow-ups interviewers ask

    • What is the MRO with multiple inheritance?
    • When is composition better?

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Inheritance in Python: Animal and Dog?

    The optimal solution runs in O(1) time and O(1) auxiliary space. Method lookup follows a fixed-length chain of classes.

    What follow-up questions do interviewers ask about Inheritance in Python: Animal and Dog?

    What is the MRO with multiple inheritance? When is composition better?