Name mangling helps protect class attributes from being changed accidentally from outside the class.
Name mangling in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
class MyClass: def __init__(self): self.__hidden = 42
Double underscores before a name trigger name mangling.
The attribute is renamed internally to include the class name.
Examples
Python
class Example: def __init__(self): self.__value = 10 obj = Example() print(obj._Example__value)
Python
class Test: def __init__(self): self.__data = 'secret' def reveal(self): return self.__data obj = Test() print(obj.reveal())
Sample Program
This program shows how name mangling hides the attribute and how to access it safely inside the class or with the mangled name.
Python
class Secret: def __init__(self): self.__hidden = 'hidden value' def show(self): return self.__hidden s = Secret() print(s.show()) # Trying to access directly will cause error try: print(s.__hidden) except AttributeError as e: print('Error:', e) # Accessing with name mangling syntax print(s._Secret__hidden)
Important Notes
Name mangling is not true privacy, just a way to avoid accidental access.
Use single underscore (_) for 'protected' attributes, double underscore (__) for name mangling.
Summary
Name mangling adds the class name to attributes starting with double underscores.
This helps avoid accidental access or name conflicts.
You can still access mangled names using _ClassName__attribute syntax if needed.
Practice
1. What does name mangling do to an attribute starting with double underscores in a Python class?
easy
Solution
Step 1: Understand double underscore prefix
Attributes starting with double underscores trigger name mangling in Python classes.Step 2: Effect of name mangling
Python adds the class name before the attribute name to avoid accidental access or conflicts.Final Answer:
It adds the class name before the attribute name to avoid conflicts. -> Option AQuick Check:
Name mangling = adds class name prefix [OK]
Hint: Double underscores add class name prefix to attribute [OK]
Common Mistakes:
- Thinking double underscores make attribute public
- Confusing name mangling with deleting attributes
- Assuming attribute name changes to uppercase
2. Which of the following is the correct way to define a private attribute using name mangling in a Python class?
easy
Solution
Step 1: Identify private attribute syntax
Private attributes use double underscores at the start of the name, like __my_attr.Step 2: Check correct assignment
Assigning with self.__my_attr = 5 correctly defines a private attribute with name mangling.Final Answer:
self.__my_attr = 5 -> Option AQuick Check:
Double underscore prefix = private attribute [OK]
Hint: Use double underscores before attribute name for private [OK]
Common Mistakes:
- Using single underscore instead of double
- Placing underscores after attribute name
- Defining private attribute as a method incorrectly
3. What will be the output of this code?
class A:
def __init__(self):
self.__x = 10
a = A()
print(hasattr(a, '__x'))
print(hasattr(a, '_A__x'))medium
Solution
Step 1: Check attribute __x existence
Due to name mangling, __x is stored as _A__x internally, so hasattr(a, '__x') returns False.Step 2: Check mangled attribute _A__x existence
hasattr(a, '_A__x') returns True because this is the mangled name storing the value.Final Answer:
False True -> Option BQuick Check:
__x hidden as _A__x = False, True [OK]
Hint: Check mangled name with _ClassName__attr [OK]
Common Mistakes:
- Assuming __x is directly accessible
- Confusing mangled name with original
- Expecting both hasattr calls to be True
4. What is the error in this code snippet?
class B:
def __init__(self):
self.__val = 5
b = B()
print(b.__val)medium
Solution
Step 1: Understand name mangling effect
__val is mangled to _B__val internally, so b.__val does not exist.Step 2: Accessing __val causes AttributeError
Trying to print b.__val raises AttributeError because the attribute is hidden by name mangling.Final Answer:
AttributeError because __val is name mangled -> Option DQuick Check:
Accessing __val directly = AttributeError [OK]
Hint: Access mangled attribute with _ClassName__attr [OK]
Common Mistakes:
- Expecting no error when accessing __val
- Thinking double underscores cause syntax error
- Confusing AttributeError with TypeError
5. Given this class:
How can you access the private attribute __data from outside the class without using the get_data method?
class C:
def __init__(self):
self.__data = 42
def get_data(self):
return self.__data
c = C()How can you access the private attribute __data from outside the class without using the get_data method?
hard
Solution
Step 1: Understand name mangling for __data
The attribute __data is stored internally as _C__data due to name mangling.Step 2: Access mangled attribute directly
You can access it from outside the class using c._C__data.Final Answer:
c._C__data -> Option CQuick Check:
Access private with _ClassName__attr [OK]
Hint: Use _ClassName__attr to access private attribute [OK]
Common Mistakes:
- Trying to access c.__data directly
- Using single underscore _data instead
- Confusing method call with attribute access
