How do private attributes and name mangling work in Python?
· Category: Python Programming
Short answer
Python uses naming conventions rather than strict access control. A single leading underscore (e.g., _value) indicates an internal attribute. A double leading underscore (e.g., __value) triggers name mangling, making it harder to access from outside the class.
Steps
- Use
_attributefor "protected" internal use. - Use
__attributeto avoid name clashes in subclasses. - Access mangled names only when truly necessary via
_ClassName__attribute.
class BankAccount:
def __init__(self, balance):
self._balance = balance
self.__pin = "1234"
def _validate(self, amount):
return amount > 0
def __hash_pin(self):
return hash(self.__pin)
account = BankAccount(100)
print(account._balance) # Accessible but discouraged
# print(account.__pin) # AttributeError
print(account._BankAccount__pin) # Works via mangled name
Tips
- Python's philosophy is "we are all consenting adults here"; conventions rely on programmer discipline.
- Properties provide a better encapsulation mechanism than name mangling for most cases.
- Use
__sparingly; it is mainly intended to prevent accidental overrides in subclasses.
Common issues
- Name mangling applies only to attributes starting with
__and not ending with__. - Mangling can break serialization and introspection tools that expect the original attribute name.
- Overusing
__creates unnecessary friction when testing or extending classes.