![]() |
VOOZH | about |
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.
Output
Jake
ERROR!
Traceback (most recent call last):
File "<main.py>", line 10, in <module>
AttributeError: 'Student' object has no attribute '__name'
Explanation:
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.
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:
Although name-mangled variables are meant to be protected, they can still be accessed using the mangled name.
Jake
Explanation:
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.
Parent class Child class
Explanation:
Use name mangling when: