What is ‘Name Mangling’ in Python?
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: