name mangling
In Python, name mangling is a mechanism that protects class and instance attributes from being accidentally overridden or accessed from outside the class.
Python does name mangling automatically when you prefix an attribute name with two underscores (__
). When an attribute begins with __
, Python changes the name of the attribute by adding an underscore and the class name to the beginning of the attribute name. For example, .__name
in a Robot
class becomes ._Robot__name
.
Note: If a name starts with two underscores and also ends with two underscores, then Python doesn’t perform name mangling. Python doesn’t do name mangling on special methods.
Name mangling makes it more challenging for subclasses or external code to access or modify these attributes. However, it doesn’t make it impossible. You can still access mangled names if you know the mangling pattern, but doing so is generally discouraged as it breaks the encapsulation principle.
Example
Here’s a quick example demonstrating name mangling:
>>> class Robot:
... def __init__(self, name):
... self.__name = name
... def get_name(self):
... return f"My name is {self.__name}"
...
>>> robot = Robot("Wall-e")
>>> robot.get_name()
'My name is Wall-e'
>>> # Attempt to access the mangled name directly
>>> robot.__name
Traceback (most recent call last):
...
AttributeError: 'Robot' object has no attribute '__name'
>>> # Access the mangled name
>>> robot._Robot__name
'Wall-e'
In this example, when you attempt to access robot.__name
directly, you get an AttributeError
because Python has changed its name to _Robot__name
.
Related Resources
Tutorial
Single and Double Underscores in Python Names
In this tutorial, you'll learn a few Python naming conventions involving single and double underscores (_). You'll learn how to use this character to differentiate between public and non-public names in APIs, write safe classes for subclassing purposes, avoid name clashes, and more.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Inheritance and Composition: A Python OOP Guide (Tutorial)
- Single and Double Underscore Naming Conventions in Python (Course)
- Single and Double Underscores in Python Names (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Inheritance and Composition: A Python OOP Guide (Course)
- Inheritance and Composition: A Python OOP Guide (Quiz)