Open In App

Name mangling in Python

Last Updated : 19 Dec, 2025
Comments
Improve
Suggest changes
12 Likes
Like
Report

In Python, name mangling prevents accidental name conflicts in classes, mainly during inheritance. It applies to variables or methods starting with two leading underscores (__) and not ending with double underscores. Python automatically renames such identifiers internally to avoid clashes, and this transformation is done by the interpreter, not the programmer.

The name is transformed into the following format:

_classname__identifier

This transformation is done by the Python interpreter, not by the programmer.

Example: This example shows how a variable with double underscores behaves inside and outside a class.

Python
class Student:
    def __init__(self, name):
        self.__name = name

    def show(self):
        print(self.__name)

s = Student("Jake")
s.show()
print(s.__name)

Output

Jake
ERROR!
Traceback (most recent call last):
File "<main.py>", line 10, in <module>
AttributeError: 'Student' object has no attribute '__name'

Explanation:

  • __name is internally changed to _Student__name.
  • Accessing __name directly from outside the class causes an error.

How Name Mangling Works Internally

The dir() function lists all valid attributes of an object, including names modified by Python. Using it helps us see how name mangling is applied internally by the interpreter.

Python
class Student:
    def __init__(self, name):
        self.__name = name

s = Student("Jake")
print(dir(s))

Output

['_Student__name', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

Explanation:

  • Python renamed __name to _Student__name internally.
  • This confirms that name mangling has taken place.

Accessing Mangled Names

Although name-mangled variables are meant to be protected, they can still be accessed using the mangled name.

Python
class Student:
     def __init__(self, name):
         self.__name = name

s = Student("Jake")
print(s._Student__name)

Output
Jake

Explanation:

  • Adding _ClassName allows access to the mangled variable.
  • This shows that name mangling is not true privacy, just a safety mechanism.

Name Mangling and Method Overriding

Name mangling is especially useful when working with inheritance. It prevents subclasses from accidentally overriding important methods.

Example: This example shows how name mangling protects a method from being overridden unintentionally.

Python
class Parent:
    def __init__(self):
       self.__show()

    def show(self):
       print("Parent class")

    __show = show

class Child(Parent):
     def show(self):
        print("Child class")

obj = Child()
obj.show()

Output
Parent class
Child class

Explanation:

  • __show is mangled to _Parent__show.
  • The parent class safely calls its own method.
  • The child class can still define its own show() without breaking the parent logic.

Key Points to Remember

  1. Name mangling applies to names starting with __.
  2. It helps avoid name conflicts in inheritance.
  3. It is not strict privacy, but a protective feature.
  4. Best used when designing classes meant to be extended.

When Should You Use Name Mangling?

Use name mangling when:

  • You want to prevent accidental overrides in subclasses
  • You are writing reusable or framework-level classes
  • You want clearer separation between internal and external attributes

Explore

Morty Proxy This is a proxified and sanitized view of the page, visit original site.