What is Double Underscore in Python: Explanation and Examples
double underscore before a variable or method name triggers name mangling, which means the name is changed internally to avoid conflicts in subclasses. This is often used to make attributes private and protect them from being accidentally overridden.How It Works
When you put two underscores before a variable or method name in a Python class, Python changes the name behind the scenes. This process is called name mangling. It adds the class name in front of the variable name to make it unique.
Think of it like labeling your belongings with your full name so no one else can confuse them with theirs. This helps protect the variable from being accidentally changed or accessed from outside the class or by subclasses.
However, this does not make the variable truly private like in some other languages; it just makes it harder to access by changing the name internally.
Example
This example shows how double underscore changes the variable name inside a class and prevents easy access from outside.
class MyClass: def __init__(self): self.__hidden = 42 # double underscore variable obj = MyClass() # Trying to access directly will cause an error try: print(obj.__hidden) except AttributeError as e: print(f"Error: {e}") # Accessing the mangled name works print(obj._MyClass__hidden)
When to Use
Use double underscore when you want to avoid name conflicts in subclasses or protect variables from being accidentally accessed or modified outside the class. It is useful in large projects or libraries where many classes may inherit from each other.
For example, if you have a base class and a subclass that both use a variable with the same name, double underscore helps keep them separate. It also signals to other developers that the variable is meant to be private.
Key Points
- Double underscore triggers name mangling to avoid naming conflicts.
- It makes variables harder to access from outside the class.
- It is not true privacy but a way to protect internal variables.
- Useful in inheritance to prevent accidental overrides.
- Accessing mangled names directly is possible but discouraged.