Encapsulation & Private Variables (`_` and `__`)
`_single` prefix signals an internal private attribute (convention). `__double` triggers name mangling (`_Class__attr`) to prevent accidental overrides.
class SecretVault:
def __init__(self, key):
self._hint = "Internal by convention"
self.__key = key # Name mangled!
v = SecretVault("pass123")
# print(v.__key) # AttributeError!
print(v._SecretVault__key) # Accessible if forced
# 120. Encapsulation & Private Variables (`_` and `__`) `_single` prefix signals an internal private attribute (convention). `__double` triggers name mangling (`_Class__attr`) to prevent accidental overrides: ```python class SecretVault: def __init__(self, key): self._hint = "Internal by convention" self.__key = key # Name mangled! v = SecretVault("pass123") # print(v.__key) # AttributeError! print(v._SecretVault__key) # Accessible if forced ``` Python follows the philosophy: "We are all consenting adults here." A single underscore `_var` tells other developers "don't touch this unless you know what you are doing." Double underscore `__var` alters the internal name in `__dict__` to prevent subclasses from accidentally trampling it.