Bird
Raised Fist0

Identify the subtle bug in the following Python code implementing a deep copy method for a Profile class: import copy class Profile: def __init__(self, name, scores): self.name = name self.scores = scores def __deepcopy__(self, memo): new_name = copy.deepcopy(self.name) new_scores = copy.deepcopy(self.scores, memo) return Profile(new_name, new_scores)

medium🐞 Bug Identification Q7 of Q15
OOP & Design Patterns - Prototype Pattern - Deep Copy vs Shallow Copy
Identify the subtle bug in the following Python code implementing a deep copy method for a Profile class: import copy class Profile: def __init__(self, name, scores): self.name = name self.scores = scores def __deepcopy__(self, memo): new_name = copy.deepcopy(self.name) new_scores = copy.deepcopy(self.scores, memo) return Profile(new_name, new_scores)
AMissing passing memo dictionary to deepcopy of name
BNot copying the scores list deeply
CReturning a new Profile instead of modifying self
DUsing copy.deepcopy instead of copy.copy
Step-by-Step Solution
Solution:
  1. Step 1: Examine deepcopy calls

    copy.deepcopy(self.name) is called without passing memo, which can cause redundant copies or infinite recursion on cyclic references.
  2. Step 2: Verify scores deepcopy call

    copy.deepcopy(self.scores, memo) correctly passes memo dictionary, avoiding repeated copies.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Always pass memo to all deepcopy calls to avoid bugs -> [OK]
Quick Trick: Pass memo dict to all deepcopy calls to avoid recursion bugs [OK]
Common Mistakes:
MISTAKES
  • Forgetting memo in deepcopy calls
  • Assuming shallow copy suffices
Trap Explanation:
PITFALL
  • Candidates miss passing memo causing subtle infinite recursion or duplicate copies.
Interviewer Note:
CONTEXT
  • Tests attention to detail in implementing deep copy methods.
Master "Prototype Pattern - Deep Copy vs Shallow Copy" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes