Bird
0
0

Consider this simplified template method code in Python:

medium📝 Analysis Q13 of 15
LLD - Behavioral Design Patterns — Part 1
Consider this simplified template method code in Python:
class Game:
    def play(self):
        self.start()
        self.play_turn()
        self.end()

    def start(self):
        print('Game started')

    def play_turn(self):
        print('Playing turn')

    def end(self):
        print('Game ended')

class Chess(Game):
    def play_turn(self):
        print('Chess turn played')

chess = Chess()
chess.play()

What will be the output when chess.play() is called?
AGame ended Chess turn played Game started
BChess turn played Game started Game ended
CGame started Playing turn Game ended
DGame started Chess turn played Game ended
Step-by-Step Solution
Solution:
  1. Step 1: Trace the play() method calls

    The play() method calls start(), play_turn(), and end() in order.
  2. Step 2: Identify overridden methods

    Chess overrides play_turn(), so Chess's version prints 'Chess turn played'. start() and end() use base class prints.
  3. Final Answer:

    Game started Chess turn played Game ended -> Option D
  4. Quick Check:

    Template calls base start/end + overridden play_turn [OK]
Quick Trick: Overridden steps print their own messages [OK]
Common Mistakes:
MISTAKES
  • Ignoring method overriding
  • Assuming base play_turn() runs
  • Mixing order of prints
  • Thinking play() is overridden

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes