Bird
Raised Fist0

Given this code snippet, what will be printed?

medium📝 Analysis Q13 of Q15
LLD - Behavioral Design Patterns — Part 1

Given this code snippet, what will be printed?

class Subject:
    def __init__(self):
        self.observers = []
        self.state = 0
    def attach(self, observer):
        self.observers.append(observer)
    def set_state(self, state):
        self.state = state
        for obs in self.observers:
            obs.update(state)

class Observer:
    def __init__(self, name):
        self.name = name
    def update(self, state):
        print(f"{self.name} received state {state}")

subject = Subject()
obs1 = Observer('A')
obs2 = Observer('B')
subject.attach(obs1)
subject.attach(obs2)
subject.set_state(5)
AA received state 5 B received state 5
BA received state 0 B received state 0
CNo output
DError: update method missing
Step-by-Step Solution
Solution:
  1. Step 1: Follow the attach and set_state calls

    Observers A and B are attached to the subject. When set_state(5) is called, it updates the state and calls update(5) on each observer.
  2. Step 2: Understand the update method output

    Each observer prints its name and the new state, so both print lines with state 5.
  3. Final Answer:

    A received state 5 B received state 5 -> Option A
  4. Quick Check:

    Observers print updated state 5 [OK]
Quick Trick: Observers print on update call with new state [OK]
Common Mistakes:
MISTAKES
  • Thinking observers print old state
  • Assuming no output without explicit print
  • Confusing method names causing errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes