Bird
0
0

You have a class with a protected dictionary attribute _settings. To allow subclasses to safely update this dictionary without replacing it, which method is best?

hard📝 Application Q8 of 15
Python - Encapsulation and Data Protection
You have a class with a protected dictionary attribute _settings. To allow subclasses to safely update this dictionary without replacing it, which method is best?
AAllow direct assignment to <code>_settings</code> from subclasses.
BProvide a method that updates keys in <code>_settings</code> instead of assigning a new dictionary.
CMake <code>_settings</code> a public attribute to simplify access.
DUse double underscore prefix to make <code>_settings</code> private.
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected attribute usage

    Protected attributes are intended for internal use and subclass access.
  2. Step 2: Safe update approach

    Providing a method to update keys inside the dictionary prevents accidental replacement of the entire dictionary.
  3. Step 3: Analyze options

    Provide a method that updates keys in _settings instead of assigning a new dictionary. is best practice; B risks replacing the dictionary; C exposes internal state; D makes attribute private, restricting subclass access.
  4. Final Answer:

    Provide a method that updates keys in _settings instead of assigning a new dictionary. -> Option B
  5. Quick Check:

    Update dictionary contents, don't replace protected attribute [OK]
Quick Trick: Update dictionary contents, don't replace protected attribute [OK]
Common Mistakes:
  • Replacing the entire dictionary instead of updating it
  • Making attribute public and losing encapsulation
  • Using double underscore and blocking subclass access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes