Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q7 of Q15
Python - Encapsulation and Data Protection
Identify the error in this code snippet:
class Data:
    def __init__(self):
        self.__info = 42
    def print_info(self):
        print(self._Data__info)

obj = Data()
print(obj.__info)
AAttributeError because __info is private and accessed directly
BSyntaxError due to incorrect print statement
CNo error, prints 42 twice
DTypeError because __info is not callable
Step-by-Step Solution
Solution:
  1. Step 1: Understand private attribute access

    The attribute __info is private and name mangled to _Data__info.
  2. Step 2: Accessing private attribute directly from instance

    Trying to print obj.__info causes AttributeError because __info is not accessible directly.
  3. Final Answer:

    AttributeError because __info is private and accessed directly -> Option A
  4. Quick Check:

    Direct access to private attribute causes AttributeError [OK]
Quick Trick: Access private attributes only via mangled name or methods [OK]
Common Mistakes:
MISTAKES
  • Expecting direct access to private attribute to work
  • Confusing mangled name with original name
  • Assuming no error occurs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes