Name mangling in Python (original) (raw)

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.

Python `

class Student: def init(self, name): self.__name = name

def show(self):
    print(self.__name)

s = Student("Jake") s.show() print(s.__name)

`

**Output

Jake
ERROR!
Traceback (most recent call last):
File "<main.py>", line 10, in
AttributeError: 'Student' object has no attribute '__name'

**Explanation:

How Name Mangling Works Internally

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.

Python `

class Student: def init(self, name): self.__name = name

s = Student("Jake") print(dir(s))

`

**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:

Accessing Mangled Names

Although name-mangled variables are meant to be protected, they can still be accessed using the mangled name.

Python `

class Student: def init(self, name): self.__name = name

s = Student("Jake") print(s._Student__name)

`

**Explanation:

Name Mangling and Method Overriding

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.

Python `

class Parent: def init(self): self.__show()

def show(self):
   print("Parent class")

__show = show

class Child(Parent): def show(self): print("Child class")

obj = Child() obj.show()

`

Output

Parent class Child class

**Explanation:

Key Points to Remember

  1. Name mangling applies to names starting with __.
  2. It helps avoid name conflicts in inheritance.
  3. It is not strict privacy, but a protective feature.
  4. Best used when designing classes meant to be extended.

When Should You Use Name Mangling?

Use name mangling when: