Bird
0
0

What will be the output of the following code?

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

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

animals = [Dog(), Cat()]
for animal in animals:
    print(animal.sound())
AMeow Bark
BBark Bark
CError: sound method not found
DBark Meow
Step-by-Step Solution
Solution:
  1. Step 1: Understand the classes and their methods

    Dog and Cat classes both have a method named sound that returns different strings.
  2. Step 2: Trace the loop calling sound on each object

    The loop calls sound() on Dog instance (returns "Bark") and Cat instance (returns "Meow"), printing each.
  3. Final Answer:

    Bark Meow -> Option D
  4. Quick Check:

    Different classes, same method name, different outputs [OK]
Quick Trick: Same method name, different classes, different outputs [OK]
Common Mistakes:
  • Assuming both calls return the same string
  • Expecting a runtime error due to method name
  • Mixing the order of outputs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes