Tools
Log in
English

Learn to codePython

Python naming and access rules

Based on Python 3.12

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.

Example code

main.py · 29 lines
class Locker:    max_tries = 3     def __init__(self, number, pin):        self.number = number        self._tries = 0        self.__pin = pin        self.is_open = False     def open(self, pin):        if self._tries >= Locker.max_tries:            return f"Locker {self.number} is locked"        if pin != self.__pin:            self._tries += 1            return f"Wrong pin ({self._tries}/{Locker.max_tries})"        self._tries = 0        self.is_open = True        return f"Locker {self.number} opened"     def __repr__(self):        return f"Locker({self.number}, open={self.is_open})"  box = Locker(12, "4821")print(box.open("0000"))print(box.open("4821"))print(sorted(vars(box)))print(box._Locker__pin == "4821", hasattr(box, "__pin"))print(box)

Python naming rules

MeaningUse from outsideIn a subclassClosest in Java
namePublic. Anyone may use itOOpublic
_nameInternal by agreement. Python does not block itWorks, but by agreement you do notOprotected
__nameRenamed with the class name to `_Locker__name`Only under the new nameNot directlyprivate
__name__Special methods Python defines (`__init__`, `__repr__`)OOnone

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

Wrong

class Locker:    def __init__(self):        self.__pin = "4821"  class SmartLocker(Locker):    def show(self):        return self.__pin  print(SmartLocker().show())

When you run itAttributeError: 'SmartLocker' object has no attribute '_SmartLocker__pin'. Did you mean: '_Locker__pin'?

Fixed

class Locker:    def __init__(self):        self._pin = "4821"  class SmartLocker(Locker):    def show(self):        return self._pin  print(SmartLocker().show())

When you run it4821

Resetting a _name from outside to dodge a rule

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.

Wrong

box = Locker(7, "1234")for _ in range(3):    box.open("0000")box._tries = 0print(box.open("1234"))

When you run itLocker 7 opened

Fixed

box = Locker(7, "1234")for _ in range(3):    box.open("0000")print(box.open("1234"))

When you run itLocker 7 is locked

Wrapping your own name in double underscores

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.

Wrong

class Locker:    def __init__(self, pin):        self.__pin__ = pin  print(Locker("4821").__pin__)

When you run it4821

Fixed

class Locker:    def __init__(self, pin):        self.__pin = pin  print(hasattr(Locker("4821"), "__pin"))

When you run itFalse

Check yourself

Question 1

What is hasattr(box, "_Locker__pin")?

box = Locker(3, "1111")print(hasattr(box, "_Locker__pin"))

Show the answer

Answer: 1. True self.__pin is stored on the object as _Locker__pin, so it is True.

Question 2

Which name is not renamed when used inside a class?

Show the answer

Answer: 2. __pin__ Two underscores in front and two at the end make it a special name, left as is. Two in front only become _ClassName__name.

Questions people ask

What is the difference between one and two underscores?

One (_name) is just an agreement that it is internal. Two (__name) make Python rename it to _Class__name so it does not clash with subclasses.

Can outside code read a __name attribute?

Yes, through the new name _Class__name. It is there to prevent accidents, not to lock anything.

What are names like __init__?

Special methods defined by Python. They are never renamed, and you should not use that pattern for your own attributes.