Bird
0
0

In Python, what effect does prefixing an instance variable with double underscores (e.g., __data) have inside a class?

easy📝 Conceptual Q1 of 15
Python - Encapsulation and Data Protection
In Python, what effect does prefixing an instance variable with double underscores (e.g., __data) have inside a class?
AIt makes the attribute a global variable
BIt triggers name mangling to make the attribute harder to access from outside the class
CIt automatically creates a property with getter and setter
DIt makes the attribute accessible only within the current method
Step-by-Step Solution
Solution:
  1. Step 1: Understand double underscore prefix

    Double underscores before an attribute name invoke Python's name mangling mechanism.
  2. Step 2: Effect of name mangling

    Name mangling changes the attribute name internally to include the class name, making it less accessible from outside.
  3. Final Answer:

    It triggers name mangling to make the attribute harder to access from outside the class -> Option B
  4. Quick Check:

    Double underscore means name mangling [OK]
Quick Trick: Double underscores trigger name mangling [OK]
Common Mistakes:
  • Confusing double underscore with making attribute global
  • Assuming it creates automatic getters/setters
  • Thinking it restricts access only within methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes