Understand Name Mangling and Internal Names
Core idea
A single leading underscore signals nonpublic intent by convention. In a class definition, a name starting with at least two underscores and not ending with at least two underscores is normally transformed by name mangling, using the class name. This helps avoid accidental name collisions; it does not prevent deliberate access.
class Sample: def __init__(self): self._count = 3
print(Sample()._count)The leading underscore does not block access. Prefer the public API when one exists.
Use a mangled name inside its class
class Sample: def __init__(self): self.__count = 4 def count(self): return self.__count
s = Sample()print(s.count())print(s._Sample__count)The method uses the transformed name; external access via that exact transformed spelling is possible. The second print is a demonstration, not a recommended public API.
Intentional failure: original spelling outside
class Sample: def __init__(self): self.__count = 4
print(Sample().__count)Outside the class definition this spelling is not transformed to _Sample__count.
Common mistake
Names such as init end with two underscores and are not mangled by this rule. Neither underscore style provides secrecy or authorization.
Practice
Create a Counter with a double-leading-underscore value and a public read method. Compare the public method with deliberate access to the transformed name; explain why it is not private security.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distinguish internal naming from access control
Check your understanding of name mangling.
What is printed?
class Box: def __init__(self): self._n = 4print(Box()._n)What is printed?
class Box: def __init__(self): self.__n = 8print(Box()._Box__n)Which exception is raised?
class Box: def __init__(self): self.__n = 8print(Box().__n)What is a suitable purpose of name mangling?