Learn Python
>>> oop_fundamentals.access_modifiers

Access Modifiers & Private Variables in Python

#concept

Unlike languages with strict public/private/protected keywords, Python signals an attribute's intended visibility purely through naming convention. A single leading underscore (_name) means "internal, please don't touch from outside," while a double leading underscore (__name) triggers name mangling, making accidental access from outside the class genuinely harder, though never fully impossible.

#how it works
1

No underscore is fully public

The normal, everyday case for most attributes.

2

A single underscore signals internal use

_name is a convention meaning "treat as private" — Python doesn’t enforce this at all.

3

A double underscore triggers name mangling

Python internally renames __name to _ClassName__name.

4

Mangling prevents accidental clashes

Its purpose is avoiding name collisions in subclasses, not providing true security.

5

Properties offer a more deliberate approach

The @property decorator gives finer control over access, covered in more advanced material.

#example
class Account:
def __init__(self, balance):
self._balance = balance
self.__pin = "1234"
 
acc = Account(100)
print(acc._balance)
print(acc._Account__pin)
Output
100
1234
1self._balance uses a single underscore — accessible from outside as acc._balance, but the underscore signals "please don’t do this directly."
2self.__pin uses a double underscore, triggering name mangling — Python actually stores it as _Account__pin internally.
3acc._Account__pin still works, proving double underscores discourage rather than truly prevent outside access — the goal is avoiding accidental clashes, not real security.
#use cases
Signaling to other developers which attributes are implementation details, not meant to be relied on from outside
Avoiding accidental attribute name clashes between a base class and a subclass, using double-underscore mangling
Understanding error messages or unexpected attribute names when debugging someone else's class
Recognizing that Python's privacy is a convention and a mild deterrent, not a hard security boundary like in some other languages

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.