Back
+10 XP
Concept

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

# 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.

Checkpoint

Does Python have true compiler-enforced `private` keywords like C++ or Java?

Practice

Create a class `Account` with an `__init__(self, balance)` that stores `self.__balance = balance`. Add a public method `get_balance(self)` that returns `self.__balance`. Instantiate `a = Account(500)` and print `a.get_balance()`.

Terminal
01
Tap code blocks below to assemble
Available Blocks