Bird
0
0

What is the error in this code snippet?

medium📝 Debug Q14 of 15
Python - Encapsulation and Data Protection
What is the error in this code snippet?
class B:
    def __init__(self):
        self.__val = 5

b = B()
print(b.__val)
ASyntaxError due to double underscores
BNo error, prints 5
CTypeError because __val is private
DAttributeError because __val is name mangled
Step-by-Step Solution
Solution:
  1. Step 1: Understand name mangling effect

    __val is mangled to _B__val internally, so b.__val does not exist.
  2. Step 2: Accessing __val causes AttributeError

    Trying to print b.__val raises AttributeError because the attribute is hidden by name mangling.
  3. Final Answer:

    AttributeError because __val is name mangled -> Option D
  4. Quick Check:

    Accessing __val directly = AttributeError [OK]
Quick Trick: Access mangled attribute with _ClassName__attr [OK]
Common Mistakes:
  • Expecting no error when accessing __val
  • Thinking double underscores cause syntax error
  • Confusing AttributeError with TypeError

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes