Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Python - Encapsulation and Data Protection
What will be the output of this code?
class A:
    def __init__(self):
        self.__x = 10

a = A()
print(hasattr(a, '__x'))
print(hasattr(a, '_A__x'))
ATrue\nTrue
BFalse\nTrue
CTrue\nFalse
DFalse\nFalse
Step-by-Step Solution
Solution:
  1. Step 1: Check attribute __x existence

    Due to name mangling, __x is stored as _A__x internally, so hasattr(a, '__x') returns False.
  2. Step 2: Check mangled attribute _A__x existence

    hasattr(a, '_A__x') returns True because this is the mangled name storing the value.
  3. Final Answer:

    False True -> Option B
  4. Quick Check:

    __x hidden as _A__x = False, True [OK]
Quick Trick: Check mangled name with _ClassName__attr [OK]
Common Mistakes:
  • Assuming __x is directly accessible
  • Confusing mangled name with original
  • Expecting both hasattr calls to be True

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes