Encapsulation
Public and Private Members
Access control conventions in Python
Interview: Python conventions — tests understanding of naming conventions, name mangling, and Pythonic encapsulation
Unlike Java or C++, Python doesn't enforce access control at the language level. Instead, it uses naming conventions to signal intended access levels. Understanding these conventions is essential for writing maintainable, Pythonic code and is frequently tested in interviews.
Access Levels in Python
- Public:
name— accessible from anywhere, no restrictions - Protected:
_name— convention: internal use only, accessible but discouraged from outside - Private:
__name— name mangling applied, accessible via_ClassName__name
Python's Philosophy
"We are all consenting adults here" — Python trusts developers to follow conventions rather than enforcing restrictions. The underscore prefix is a signal, not a barrier. Name mangling prevents accidental name collisions in inheritance, not intentional access.
Common Pitfall
Double underscore __name is NOT truly private — it can always be accessed via _ClassName__name. Name mangling prevents accidental conflicts in inheritance, not intentional access.
Use Cases
Designing clean public APIs with hidden implementation details
Preventing accidental attribute conflicts in inheritance hierarchies
Module-level access control with __all__ and underscore prefixes
Library design: stable public interface, flexible protected internals
Encapsulating sensitive data (API keys, tokens) behind methods
Common Mistakes
Thinking __name is truly private (it can be accessed via mangled name)
Using __name everywhere when _name convention would suffice
Not respecting the _name convention and accessing protected members from outside
Forgetting that name mangling uses the class where the attribute was DEFINED, not accessed
Using Java-style getters/setters for everything instead of Pythonic attribute access