Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Encapsulation and Data Protection
What will be the output of this code?
class Test:
    def __init__(self):
        self.__val = 5

t = Test()
print(hasattr(t, '__val'))
print(hasattr(t, '_Test__val'))
AFalse\nTrue
BFalse\nFalse
CTrue\nFalse
DTrue\nTrue
Step-by-Step Solution
Solution:
  1. Step 1: Check attribute names

    __val is mangled to _Test__val internally.
  2. Step 2: Check hasattr results

    t does not have '__val' attribute, so False; but has '_Test__val', so True.
  3. Final Answer:

    False\nTrue -> Option A
  4. Quick Check:

    hasattr('__val')=False, hasattr('_Test__val')=True [OK]
Quick Trick: hasattr('__attr') is False; use mangled name to check [OK]
Common Mistakes:
  • Assuming __val exists as is
  • Confusing mangled and original names
  • 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