0
0
PythonConceptBeginner · 3 min read

What is Name Mangling in Python: Explanation and Examples

In Python, name mangling is a way the interpreter changes the names of class attributes that start with double underscores to make them harder to access from outside the class. This helps avoid accidental name conflicts in subclasses by internally renaming the attribute with the class name prefix.
⚙️

How It Works

Name mangling in Python happens when you create a class attribute with two leading underscores and no trailing underscores, like __hidden. Python changes this name internally by adding the class name in front, turning it into something like _ClassName__hidden. This makes it harder to accidentally access or override this attribute from outside the class or in subclasses.

Think of it like putting a label on a personal item in a shared room. The label (class name) helps keep your item (attribute) separate from others with similar names. This is not true privacy but a way to avoid accidental clashes in bigger programs.

💻

Example

This example shows how Python changes the name of a double underscore attribute inside a class to prevent outside access by its original name.

python
class MyClass:
    def __init__(self):
        self.__secret = 'hidden value'

obj = MyClass()

# Trying to access __secret directly will cause an error
try:
    print(obj.__secret)
except AttributeError as e:
    print(e)

# Accessing the mangled name works
print(obj._MyClass__secret)
Output
'MyClass' object has no attribute '__secret' hidden value
🎯

When to Use

Name mangling is useful when you want to avoid your class attributes being accidentally overridden or accessed from outside, especially in large projects or when creating subclasses. It helps protect internal details of a class without making them completely private.

Use it when you want to signal that an attribute is meant for internal use only and should not be touched directly by users of your class or subclasses. However, remember it is not true security, just a way to reduce mistakes.

Key Points

  • Name mangling applies only to attributes with two leading underscores and no trailing underscores.
  • It changes the attribute name by prefixing it with _ClassName.
  • This helps avoid name conflicts in subclasses and accidental external access.
  • It is a convention for internal use, not a strict privacy feature.

Key Takeaways

Name mangling changes double underscore attribute names to include the class name prefix.
It helps prevent accidental access or overriding of internal class attributes.
Use it to signal attributes meant for internal use, especially in inheritance scenarios.
Name mangling is not true privacy but a helpful naming convention.
Access to mangled names is still possible if needed, but discouraged.