Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q5 of Q15
Python - Encapsulation and Data Protection
What will be the output of this code?
class Test:
    def __init__(self):
        self.__value = 10
    def change_value(self):
        self.__value = 20
obj = Test()
obj.change_value()
print(obj._Test__value)
A20
B10
CAttributeError
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Initialize private attribute

    The private attribute __value is set to 10 in the constructor.
  2. Step 2: Modify private attribute inside method

    The method change_value() changes __value to 20.
  3. Step 3: Access private attribute using mangled name

    Accessing obj._Test__value returns the updated value 20.
  4. Final Answer:

    20 -> Option A
  5. Quick Check:

    Private attribute updated and accessed via mangled name [OK]
Quick Trick: Private attribute changes reflect when accessed via mangled name [OK]
Common Mistakes:
MISTAKES
  • Expecting original value 10 after change
  • Trying to access __value directly causing error
  • Confusing attribute names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes