Bird
0
0

Consider this code:

hard📝 Application Q9 of 15
Python - Encapsulation and Data Protection
Consider this code:
class Secret:
    def __init__(self):
        self.__data = 123
    def reveal(self):
        return self.__data

s = Secret()
print(s._Secret__data)
s.__data = 456
print(s.reveal())

What is the output?
A123\n456
B123\n123
C456\n456
DAttributeError
Step-by-Step Solution
Solution:
  1. Step 1: Access private attribute via mangled name

    Printing s._Secret__data outputs 123, the original private value.
  2. Step 2: Assign new attribute __data externally

    Setting s.__data = 456 creates a new public attribute, not changing the private one.
  3. Step 3: Calling reveal() returns original private attribute

    The method reveal() returns the private __data, still 123.
  4. Final Answer:

    123 123 -> Option B
  5. Quick Check:

    External __data creates new attribute, private remains unchanged [OK]
Quick Trick: External __attr creates new attribute, private stays intact [OK]
Common Mistakes:
  • Assuming external __data overwrites private attribute
  • Expecting reveal() to return new value
  • Confusing mangled and normal attributes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes