← Back

Home β€Ί Problems β€Ί Cow overrides speak()

Cow overrides speak()

🧠 Predict the output Topic: oop Difficulty: medium Free

What this problem practises

Object-oriented bugs hide in state: class attributes shared by every instance, mutable defaults declared in __init__ signatures, and methods that mutate self when the caller expected a copy.

This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.

Difficulty: medium β€” expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.

The challenge

What will this program print? Type the exact output.

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The snippet

The interactive editor pre-fills exactly this code β€” read it, then submit your prediction:

class Animal:
    def speak(self):
        return '...'
class Cow(Animal):
    def speak(self):
        return 'moo'
d = Cow()
print(d.speak())

Understand the rule

When a subclass defines a method with the exact same name as its parent class, Python uses dynamic method resolution (MRO) at call time. The runtime type of the instance β€” not the base class it inherited from β€” decides which `speak()` implementation runs.

How to trace it

  1. Python inspects the class of the object on which `.speak()` is called (for example, `Cow`).
  2. Method lookup checks `Cow.__dict__` first before walking up the inheritance chain to the parent class.
  3. Because `Cow` defines its own `speak(self)` method, lookup succeeds immediately on the child class.
  4. Unless the child explicitly calls `super().speak()`, the parent class's `speak()` body never executes for that call.

Common wrong fixes

Rule to remember

In Python inheritance, attribute lookup always starts on `type(obj)` β€” a child method completely replaces the parent's version unless `super()` is called.

Solve it in the interactive editor β†’

More oop problems

Keep going