Does Python have private attributes? What do _x and __x mean?
Python has no true private. A single underscore _x is a hint that it is internal. A double underscore __x triggers name mangling, which renames it to _ClassName__x to avoid clashes in subclasses.
Explain it simply
Python trusts programmers. A single leading underscore is a "staff only" sign: nothing stops you, but you were told. A double underscore does something real: Python rewrites the name so a subclass using the same name does not accidentally overwrite it.
Mangling is for avoiding accidents, not for security. Anyone can still reach the renamed attribute.
Example
class Account:
def __init__(self):
self._audit = "internal hint"
self.__pin = 1234
acc = Account()
print(acc._audit) # internal hint
# print(acc.__pin) # AttributeError
print(acc._Account__pin) # 1234 (mangled name still reachable)
print([n for n in vars(acc)]) # ['_audit', '_Account__pin']For controlled access use a @property, which lets you add validation later without changing how callers write obj.value.
What to say in the interview
"Python relies on convention: _x means internal use, and __x is name-mangled to _Class__x to prevent subclass collisions. Neither is enforced privacy. For controlled access I use properties."
Common mistakes
- Using __x and believing it makes the value secure.