Encapsulation
Name Mangling
Double underscore prefix and attribute name transformation
Interview: Python internals — tests deep understanding of name mangling mechanism and its purpose in inheritance
Name mangling is Python's mechanism that transforms attribute names starting with double underscores (__name) into _ClassName__name. This prevents name collisions in inheritance hierarchies where parent and child classes might accidentally use the same attribute name. It's a common source of confusion in interviews.
How Mangling Works
__namein classFoobecomes_Foo__name- Mangling uses the class where the name was defined, not where it's accessed
- Names ending with double underscore are NOT mangled (e.g.,
__init__) - Single underscore names are NOT mangled (just a convention)
- Mangling applies to methods as well as attributes
Purpose: Inheritance Collision Prevention
The primary purpose of name mangling is NOT to make things private, but to prevent accidental name collisions in inheritance hierarchies. Each class's __name becomes unique to that class.
Interview Tip
A classic interview question: "What does c._Parent__value return when both Parent and Child define __value?" — Answer: the Parent's value, because each class's __value is mangled to a different name.
Use Cases
Preventing attribute name collisions in complex inheritance hierarchies
Framework internals: base classes protecting their attributes from subclass conflicts
Understanding why __method in child doesn't override parent's __method
Debugging unexpected AttributeError in inheritance chains
Library design: protecting internal state from accidental override
Common Mistakes
Thinking __name makes things truly private (it's just name mangling)
Expecting __method in child to override parent's __method (it doesn't)
Not knowing you can access mangled names via _ClassName__name
Using __name when _name convention would be more appropriate
Forgetting that dunder methods (__init__, __str__) are NOT mangled