Bird
0
0

What will happen when this code runs?

medium📝 Predict Output Q5 of 15
Python - Polymorphism and Dynamic Behavior
What will happen when this code runs?
class Cat:
    def speak(self):
        print('Meow!')

class Robot:
    def speak(self):
        print('Beep!')

def talk(entity):
    entity.speak()

talk(Cat())
talk(Robot())
AError on second call
BNo output
COnly 'Meow!' is printed
DMeow!\nBeep!
Step-by-Step Solution
Solution:
  1. Step 1: Check methods in both classes

    Both Cat and Robot have a speak method printing different sounds.
  2. Step 2: Trace function calls

    Calling talk(Cat()) prints 'Meow!'. Calling talk(Robot()) prints 'Beep!'.
  3. Final Answer:

    Meow!\nBeep! -> Option D
  4. Quick Check:

    Duck typing allows different objects with same method [OK]
Quick Trick: Different classes can share method names for duck typing [OK]
Common Mistakes:
  • Expecting error due to different classes
  • Thinking only one call prints output
  • Confusing method names or outputs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes