Bird
Raised Fist0

How can you modify this constructor to accept a list of hobbies and store a copy to avoid external changes?

hard🚀 Application Q9 of Q15
Python - Constructors and Object Initialization
How can you modify this constructor to accept a list of hobbies and store a copy to avoid external changes?
class User:
    def __init__(self, name, hobbies):
        self.name = name
        self.hobbies = hobbies
Aself.hobbies = hobbies.append([])
Bself.hobbies = hobbies
Cself.hobbies = hobbies.copy()
Dself.hobbies = hobbies.extend([])
Step-by-Step Solution
Solution:
  1. Step 1: Understand shared mutable references

    Assigning hobbies directly links to the original list, so changes outside affect the object.
  2. Step 2: Use copy to avoid shared references

    Using hobbies.copy() creates a new list, protecting the object's data.
  3. Final Answer:

    self.hobbies = hobbies.copy() -> Option C
  4. Quick Check:

    Copy mutable inputs to avoid side effects [OK]
Quick Trick: Copy mutable inputs to protect object data [OK]
Common Mistakes:
MISTAKES
  • Assigning mutable objects directly
  • Using mutating methods like append/extend for copying
  • Confusing list copy methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes