Bird
0
0

Find the error in this code related to encapsulation:

medium📝 Debug Q14 of 15
Python - Encapsulation and Data Protection
Find the error in this code related to encapsulation:
class Person:
    def __init__(self, name):
        self.__name = name

p = Person('Anna')
print(p.__name)
AAttributeError because __name is private
BSyntaxError due to private variable
CNo error, prints 'Anna'
DTypeError because __name is missing
Step-by-Step Solution
Solution:
  1. Step 1: Identify private variable usage

    The variable __name is private and cannot be accessed directly outside the class.
  2. Step 2: Analyze print statement

    Trying to print p.__name causes AttributeError because it is private.
  3. Final Answer:

    AttributeError because __name is private -> Option A
  4. Quick Check:

    Private variables cause AttributeError on direct access [OK]
Quick Trick: Private variables cause AttributeError if accessed directly [OK]
Common Mistakes:
  • Thinking private variables print normally
  • Confusing syntax error with attribute error
  • Trying to access private variables without methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes