Bird
Raised Fist0

Given this class:

hard🚀 Application Q15 of Q15
Python - Encapsulation and Data Protection
Given this class:
class C:
    def __init__(self):
        self.__data = 42
    def get_data(self):
        return self.__data

c = C()

How can you access the private attribute __data from outside the class without using the get_data method?
Ac.__data
Bc._data
Cc._C__data
Dc.get_data()
Step-by-Step Solution
Solution:
  1. Step 1: Understand name mangling for __data

    The attribute __data is stored internally as _C__data due to name mangling.
  2. Step 2: Access mangled attribute directly

    You can access it from outside the class using c._C__data.
  3. Final Answer:

    c._C__data -> Option C
  4. Quick Check:

    Access private with _ClassName__attr [OK]
Quick Trick: Use _ClassName__attr to access private attribute [OK]
Common Mistakes:
MISTAKES
  • Trying to access c.__data directly
  • Using single underscore _data instead
  • Confusing method call with attribute access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes