Name mangling is a technique used in Python to make attribute names in a class unique, especially in cases of inheritance. This is primarily used to avoid name conflicts in subclasses.
1. Understanding Name Mangling
In Python, name mangling refers to the alteration of variable names that start with double underscores __> in order to make them more unique and to prevent accidental access from outside the class. This is done by the interpreter and is primarily intended for internal use by the class itself.
2. How Name Mangling Works
When a variable or method name starts with two underscores and does not end with two underscores, Python performs name mangling. The interpreter changes the name of the variable to include the class name, making it more difficult to accidentally override in subclasses.
Example of Name Mangling
class Base:
def __init__(self):
self.__private_var = "I'm private"
def get_private_var(self):
return self.__private_var
class Derived(Base):
def __init__(self):
super().__init__()
self.__private_var = "I'm private in derived"
# Create instances
base_instance = Base()
derived_instance = Derived()
print(base_instance.get_private_var()) # Output: I'm private
print(derived_instance.get_private_var()) # Output: I'm private
# Attempt to access the mangled name
print(base_instance._Base__private_var) # Output: I'm private
print(derived_instance._Base__private_var) # Output: I'm private
print(derived_instance._Derived__private_var) # Output: I'm private in derived
3. Accessing Mangled Names
Although name mangling makes it harder to access these variables, they are still accessible using their mangled names. However, it is generally discouraged to access or modify these variables outside their class, as it breaks encapsulation principles.
4. Differences Between Single and Double Underscores
It's important to distinguish between single and double underscores:
- Single Underscore (
_var
): This is a convention used to indicate that a variable or method is intended for internal use and should be treated as private by convention, but it is not enforced by the interpreter. - Double Underscore (
__var
): This triggers name mangling, where the variable name is altered to include the class name to avoid conflicts with names in subclasses.
5. Conclusion
Name mangling in Python is a useful feature for managing name conflicts in class hierarchies and is particularly important in large codebases with complex inheritance structures. It helps in maintaining encapsulation by making private variables and methods less accessible from outside the class.