Python Double-Underscore Attributes Are Name-Mangled, Not Private
Encapsulation bundles an object's data with the methods that work on it and controls how outside code changes that data. Python has no private keyword: an attribute named self.__x is renamed to _ClassName__x (name mangling) to avoid clashes in subclasses, but it remains reachable. The Pythonic tools for encapsulation are a single underscore by convention and @property.
What Double Underscores Really Do
class Enemy:
def __init__(self, kind):
self.__kind = kind # stored as self._Enemy__kind
e = Enemy("Vampire")
e.__kind = "Ogre" # creates a NEW attribute named __kind
print(e._Enemy__kind) # Vampire: the original is untouched but reachable
The Pythonic Pattern: Underscore plus Property
class Enemy:
def __init__(self, kind, health_points=10):
self._kind = kind # "internal", by convention
self.health_points = health_points
@property
def kind(self): # read access: e.kind
return self._kind
@kind.setter
def kind(self, value): # write access with validation
if not value:
raise ValueError("kind must not be empty")
self._kind = value
Leave out the setter to make the attribute read-only. Callers keep plain attribute syntax (e.kind), and validation can be added later without changing them, unlike Java-style get_kind()/set_kind() methods.
Why Encapsulate at All
- Related data and behaviour live together.
- Invariants hold: a value can't be set to something invalid.
- The internal representation can change without breaking callers.
References
- Programming Languages MOC - hub for language notes.
- Python documentation: Private variables - name mangling and the underscore convention.
- Python documentation: property - getters, setters and read-only attributes.
Review cards
Flashcard Outside the class, e.__kind = 'Ogre' leaves the enemy's kind unchanged. Why?
Name mangling only happens inside the class body, where self.__kind becomes self._Enemy__kind. Outside it, e.__kind creates a new, unrelated attribute.