Bird
Raised Fist0

Identify the bug in the following Python code implementing deep copy for the Profile class:

medium🐞 Bug Identification Q14 of Q15
OOP & Design Patterns - Prototype Pattern - Deep Copy vs Shallow Copy
Identify the bug in the following Python code implementing deep copy for the Profile class:
import copy

class Profile:
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores

    def __deepcopy__(self, memo):
        new_name = self.name  # Bug here
        new_scores = copy.deepcopy(self.scores, memo)
        return Profile(new_name, new_scores)

original = Profile('Alice', [10, 20])
copy_obj = copy.deepcopy(original)
copy_obj.scores.append(30)
print(original.scores)
ALine assigning new_name = self.name does not deepcopy the name string
BLine assigning new_scores = copy.deepcopy(self.scores, memo) incorrectly copies scores
CThe __init__ method does not initialize scores properly
DThe return statement returns a new Profile instead of modifying self
Step-by-Step Solution
  1. Step 1: Examine __deepcopy__ method

    The line new_name = self.name copies the reference to the name string instead of deep copying it.
  2. Step 2: Understand impact

    Strings are immutable in Python, so shallow copy is usually safe, but if name were a mutable object, this would cause shared references and bugs. Proper deep copy should be used for consistency.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Only new_name assignment lacks deepcopy -> subtle bug [OK]
Quick Trick: All nested fields must be deep copied consistently [OK]
Common Mistakes:
MISTAKES
  • Forgetting to deepcopy all nested fields, assuming immutables are safe
Trap Explanation:
PITFALL
  • Candidates assume immutable fields don't need deepcopy, ignoring future mutability or consistency.
Interviewer Note:
CONTEXT
  • Checks attention to detail in overriding clone methods and understanding deep copy requirements.
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