Bird
Raised Fist0

Which of the following is the best practice to access a protected attribute _data from a subclass?

easy🧠 Conceptual Q2 of Q15
Python - Encapsulation and Data Protection
Which of the following is the best practice to access a protected attribute _data from a subclass?
AAccess it using a global variable.
BAccess it using <code>self.__data</code> inside the subclass.
CAccess it using <code>self.data</code> without underscore.
DAccess it directly using <code>self._data</code> inside the subclass.
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected attribute access

    Protected attributes (single underscore) are intended to be accessed within the class and its subclasses directly using self._data.
  2. Step 2: Differentiate from private attributes

    Double underscore attributes are name-mangled and not directly accessible; single underscore attributes are accessible directly.
  3. Final Answer:

    Access it directly using self._data inside the subclass. -> Option D
  4. Quick Check:

    Subclass accesses protected attribute with self._attribute [OK]
Quick Trick: Use self._attribute to access protected members in subclasses [OK]
Common Mistakes:
MISTAKES
  • Using double underscore to access protected attribute
  • Trying to access without underscore
  • Using global variables incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes