Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Python - Polymorphism and Dynamic Behavior
What will be the output of this code?
class Animal:
    def sound(self):
        return "Some sound"

class Dog(Animal):
    def sound(self):
        return "Bark"

class Cat(Animal):
    def sound(self):
        return "Meow"

animals = [Dog(), Cat(), Animal()]
for a in animals:
    print(a.sound())
ABark\nMeow\nSome sound
BSome sound\nSome sound\nSome sound
CBark\nMeow\nError
DError\nError\nError
Step-by-Step Solution
Solution:
  1. Step 1: Identify method overriding

    Dog and Cat classes override sound method to return "Bark" and "Meow" respectively.
  2. Step 2: Trace the loop output

    Loop calls sound() on Dog(), Cat(), and Animal() objects, printing "Bark", "Meow", and "Some sound".
  3. Final Answer:

    Bark Meow Some sound -> Option A
  4. Quick Check:

    Overridden methods print their own sounds [OK]
Quick Trick: Child method overrides parent, prints child's return [OK]
Common Mistakes:
  • Assuming parent method always runs
  • Expecting errors from calling base class method
  • Mixing output order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes