0
0
Pythonprogramming~5 mins

Name mangling in Python

Choose your learning style9 modes available
Introduction

Name mangling helps protect class attributes from being changed accidentally from outside the class.

When you want to hide a class attribute from outside access.
When you want to avoid name conflicts in subclasses.
When you want to make an attribute private but still accessible inside the class.
When you want to prevent accidental overwriting of attributes in large projects.
Syntax
Python
class MyClass:
    def __init__(self):
        self.__hidden = 42

Double underscores before a name trigger name mangling.

The attribute is renamed internally to include the class name.

Examples
You can access the mangled attribute using _ClassName__attribute syntax.
Python
class Example:
    def __init__(self):
        self.__value = 10

obj = Example()
print(obj._Example__value)
The mangled attribute is accessible inside the class methods.
Python
class Test:
    def __init__(self):
        self.__data = 'secret'

    def reveal(self):
        return self.__data

obj = Test()
print(obj.reveal())
Sample Program

This program shows how name mangling hides the attribute and how to access it safely inside the class or with the mangled name.

Python
class Secret:
    def __init__(self):
        self.__hidden = 'hidden value'

    def show(self):
        return self.__hidden

s = Secret()
print(s.show())

# Trying to access directly will cause error
try:
    print(s.__hidden)
except AttributeError as e:
    print('Error:', e)

# Accessing with name mangling syntax
print(s._Secret__hidden)
OutputSuccess
Important Notes

Name mangling is not true privacy, just a way to avoid accidental access.

Use single underscore (_) for 'protected' attributes, double underscore (__) for name mangling.

Summary

Name mangling adds the class name to attributes starting with double underscores.

This helps avoid accidental access or name conflicts.

You can still access mangled names using _ClassName__attribute syntax if needed.