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

  1. Use _attribute for "protected" internal use.
  2. Use __attribute to avoid name clashes in subclasses.
  3. 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.