What is ‘Name Mangling’ in Python?

Arun Suresh Kumar
PythonIQ
Published in
2 min readDec 30, 2022

Photo by Towfiqu barbhuiya on Unsplash

Name mangling is a technique we use to protect instance variables from being accidentally overwritten or shadowed by instance variables with the same name in derived classes. Name mangling works by adding a double underscore prefix to the name of an instance variable, and replacing any occurrences of the underscore character in the name with an underscore and the class name.

For example, consider the following Python class:

class Example:
def __init__(self):
self.__name = "Example"

In this class, the instance variable __name is protected by name mangling. If you try to access the __name variable directly from an instance of the Example class, you will get an error:

example = Example()
print(example.__name) # AttributeError: 'Example' object has no attribute '__name'

To access the __name variable from an instance of the Example class, you need to use the name mangling syntax, which involves adding an underscore and the class name to the name of the variable:

print(example._Example__name)  # Example

Name mangling is used to protect instance variables from being accidentally overwritten or shadowed by instance variables with the same name in derived classes. For example, consider the following Python class hierarchy:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Arun Suresh Kumar
PythonIQ

Technology enthusiast, Python developer, Corporate leader | https://www.linkedin.com/in/yeaske/ | Amateur chef ➜ https://instagr.am/yeaske/