Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Object-oriented PythonMiddleCommonTheory

What is the practical difference between a single leading underscore and a double leading underscore on an attribute name?

Answer

A single leading underscore, like `_value`, is purely a convention meaning "internal, please do not touch from outside the class," with no enforcement by the interpreter at all. A double leading underscore (without a trailing double underscore), like `__value`, triggers name mangling: Python rewrites the name internally to `_ClassName__value`, which is meant to avoid accidental attribute clashes in subclasses rather than to provide real privacy, since the mangled name is still fully accessible if you know the pattern.

Strong answer includes

  • single underscore is convention only, not enforced
  • double underscore triggers name mangling to _ClassName__value
  • mangling avoids subclass clashes, is not real privacy

Practical example

Inside

Python example
class Account: def __init__(self): self.__balance = 0

, the attribute is actually stored as `_Account__balance` , so `account._Account__balance` still reads it from outside the class.

#encapsulation#naming-conventions

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsPEP 8 — Style Guide for Python CodePython Software Foundation · Naming, layout and readability conventions