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
- Python inspects the class of the object on which `.speak()` is called (for example, `Cow`).
- Method lookup checks `Cow.__dict__` first before walking up the inheritance chain to the parent class.
- Because `Cow` defines its own `speak(self)` method, lookup succeeds immediately on the child class.
- Unless the child explicitly calls `super().speak()`, the parent class's `speak()` body never executes for that call.
Common wrong fixes
- Assuming both the parent's `speak()` and the child's `speak()` run automatically one after the other.
- Forgetting whether `speak()` prints directly (`print(...)`) or returns a string that the caller then passes to `print()`.
- Mixing up which variable holds a base-class instance versus a subclass instance when iterating over a list of objects.
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.
More oop problems
- AttributeError: missing self medium
- Counter object adds up medium
- Counter object adds up medium
Keep going
- Output-prediction strategies β how to predict tricky snippets without running them.
- Browse every oop problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.