What name, _name, __name and __name__ mean in Python, with a locker example.
In one line
Python has no public or private keywords. Leading underscores signal how a name should be used: one underscore is an agreement, two trigger renaming.
Why you need it
If anyone can reset a locker's failed-try count to 0, the lock-after-three-tries rule means nothing. Yet Python offers no way to lock a value completely.
So names carry the signal. _tries says "do not touch", and __pin is renamed so a subclass using the same name cannot overwrite it. The agreement only works if the whole team keeps it.
Everyday picture
Picture an office fridge. Drinks with no label are for anyone (public); ones with a "Dev team" sticker are for that team (_). There is no padlock, but people respect it. __ is a label that also writes the team name so drinks with the same name never get mixed up.
Press Run to try your edited code right away. The step-through and the output above follow the original code.
Python naming rules
Meaning
Use from outside
In a subclass
Closest in Java
name
Public. Anyone may use it
O
O
public
_name
Internal by agreement. Python does not block it
Works, but by agreement you do not
O
protected
__name
Renamed with the class name to `_Locker__name`
Only under the new name
Not directly
private
__name__
Special methods Python defines (`__init__`, `__repr__`)
O
O
none
A module-level name such as _helper is skipped by from module import *. To list what a module exports, set __all__ = ["name", ...].
When to use it
Names meant for outside use: no underscore
Values and helper methods used only inside the class: _name
Only when a deep hierarchy might reuse a name: __name
Treating __name as Java's private and using it everywhere makes subclasses awkward to write. A single underscore is enough most of the time.
Common mistakes
Using the parent's __name in a subclass
Inside the child, self.__pin becomes _SmartLocker__pin, so it cannot find the parent's _Locker__pin. Values shared with subclasses get a single underscore (_pin).
Setting _tries back to 0 reopens a locker that locked after three bad codes. A single underscore marks a value with internal rules, so outside code should neither read nor write it.
With two trailing underscores, as in __pin__, nothing is renamed and the value is public. That form is reserved for Python's special names, so keep it off your own attributes.