Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q6 of Q15
Python - Encapsulation and Data Protection
Identify the error in this code snippet:
class Container:
    def __init__(self):
        self._items = [1, 2, 3]

    def get_items(self):
        return self.__items

c = Container()
print(c.get_items())
AThere is no error; the code will print [1, 2, 3].
BThe attribute _items should be accessed as self._items, not self.__items.
CThe attribute _items is not initialized properly.
DThe method tries to access a non-existent private attribute __items.
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute naming

    Single underscore _items is different from double underscore __items.
  2. Step 2: Analyze method get_items

    The method tries to return self.__items, which does not exist because the attribute is named _items.
  3. Step 3: Result

    This causes an AttributeError at runtime.
  4. Final Answer:

    The method tries to access a non-existent private attribute __items. -> Option D
  5. Quick Check:

    Double underscore triggers name mangling; attribute name mismatch [OK]
Quick Trick: Double underscore causes name mangling; attribute name mismatch [OK]
Common Mistakes:
MISTAKES
  • Confusing single and double underscore attributes
  • Assuming __items and _items are the same
  • Ignoring AttributeError from wrong attribute name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes