Sitemap

Python Mangling

1 min readSep 11, 2025

--

I was building a python practice project based on OOP (Object Oriented Programming) paradigm, then I discovered an interesting feature in python called Name Mangling.

Name mangling is a mechanism Python uses to change the names of variables or methods that start with double underscores (__) to avoid naming conflicts in subclasses.

Get Chaanakyaa’s stories in your inbox

Join Medium for free to get updates from this writer.

In simple terms, name mangling is used to make class variables “private” — meaning they’re intended to be inaccessible from outside the class.

The Truth:

Python doesn’t have true private variables. Instead, Python uses name mangling to make it harder (but not impossible) to accidentally access or override internal variables from outside the class or in subclasses.

NOTE: Methods like __init__ or __str__ are not mangled because they’re special methods reserved by Python.

class Parent:
def __init__(self):
self.__data = "Private"

def get_data(self):
return self.__data

class Child(Parent):
pass

c = Child()
p = Parent()
print(c.get_data()) # Output: Private
print(p._Parent__data) # Output: Private
print(c._Parent__data) # Output: Private
print(c.__data) # AttributeError
print(c._Child__data) # AttributeError (since Child has no __data)

Name mangling is a unique feature in Python that provides a way to protect variables from accidental access or overrides in subclasses. It’s a convention enforced by the interpreter to encourage cleaner, safer code but is not foolproof privacy.

--

--