Bird
0
0

Which of the following is the correct way to define a Memento class in Python to store a state string?

easy🧠 Conceptual Q3 of 15
LLD - Behavioral Design Patterns — Part 2
Which of the following is the correct way to define a Memento class in Python to store a state string?
Aclass Memento: def __save__(self, state): self._state = state
Bclass Memento: def __init__(self, state): self._state = state
Cclass Memento: def __init__(self): self.state = None
Dclass Memento: def save(self, state): self.state = state
Step-by-Step Solution
Solution:
  1. Step 1: Understand Memento class structure

    The Memento class should have an initializer that accepts the state and stores it privately.
  2. Step 2: Check options for correct syntax and encapsulation

    class Memento: def __init__(self, state): self._state = state correctly defines __init__ with a private variable _state. Others either use wrong method names or do not initialize state properly.
  3. Final Answer:

    class Memento:\n def __init__(self, state):\n self._state = state -> Option B
  4. Quick Check:

    Correct Memento init = class Memento: def __init__(self, state): self._state = state [OK]
Quick Trick: Use __init__ to set private state in Memento [OK]
Common Mistakes:
MISTAKES
  • Using wrong method names like __save__
  • Not initializing state in constructor
  • Making state public without underscore

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes