Sitemap
PythonIQ

Take your Python coding to the next level and learn from others with these practical, thought-provoking, and insightful articles. We’re all about programming in Python.

Member-only story

What is ‘Name Mangling’ in Python?

--

Press enter or click to view image in full size
a lock to represent protection offered by name mangling in python
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:

--

--

Arun Suresh Kumar
Arun Suresh Kumar

Written by Arun Suresh Kumar

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

PythonIQ
PythonIQ

Published in PythonIQ

Take your Python coding to the next level and learn from others with these practical, thought-provoking, and insightful articles. We’re all about programming in Python.