Bird
Raised Fist0

What will be the output of this code when notify_observers is called?

medium📝 Analysis Q5 of Q15
LLD - Design — Online Shopping Cart
What will be the output of this code when notify_observers is called?
class Subject:
    def __init__(self):
        self.observers = set()
    def add_observer(self, obs):
        self.observers.add(obs)
    def notify_observers(self):
        for obs in self.observers:
            obs.update()

class Observer:
    def update(self):
        print('Notified')

subject = Subject()
obs1 = Observer()
obs2 = Observer()
subject.add_observer(obs1)
subject.add_observer(obs2)
subject.add_observer(obs1)
subject.notify_observers()
ANotified
BNotified Notified Notified
CNotified Notified
DError due to duplicate observer
Step-by-Step Solution
Solution:
  1. Step 1: Understand observer storage type

    Observers are stored in a set, which automatically removes duplicates.
  2. Step 2: Count unique observers notified

    Two unique observers are added; the duplicate addition of obs1 is ignored.
  3. Final Answer:

    Notified Notified -> Option C
  4. Quick Check:

    Set removes duplicates = 2 notifications [OK]
Quick Trick: Sets prevent duplicate observers [OK]
Common Mistakes:
MISTAKES
  • Expecting three notifications due to duplicate add
  • Thinking duplicate causes error
  • Assuming only one notification

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes