I try to use spam and I get an error about SomeClassNamespam.
PythonLevel: Intermediate
I try to use __spam and I get an error about _SomeClassName__spam.
Hints
- Identify object types, mutability and execution order.
- Trace a minimal example: which values and references change?
Answer
Variable names with double leading underscores are “mangled” to provide a simple
but effective way to define class private variables. Any identifier of the form
__spam (at least two leading underscores, at most one trailing underscore)
is textually replaced with _classname__spam, where classname is the
current class name with any leading underscores stripped.
The identifier can be used unchanged within the class, but to access it outside the class, the mangled name must be used:
class A:
def __one(self):
return 1
def two(self):
return 2 * self.__one()
class B(A):
def three(self):
return 3 * self._A__one()
four = 4 * A()._A__one()
In particular, this does not guarantee privacy since an outside user can still deliberately access the private attribute; many Python programmers never bother to use private variable names at all.
See also
The private name mangling specifications for details and special cases.
Source and licence: Python 3.14.0 Programming FAQ — Python Software Foundation · PSF-2.0