Bird
Raised Fist0
Pythonprogramming~20 mins

Name mangling in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Name Mangling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code using name mangling?
Consider this Python class with a double underscore attribute. What will be printed when accessing the mangled attribute directly?
Python
class MyClass:
    def __init__(self):
        self.__hidden = 42

obj = MyClass()
print(obj._MyClass__hidden)
ASyntaxError
BAttributeError
CNone
D42
Attempts:
2 left
💡 Hint
Double underscore attributes are renamed internally with the class name prefix.
Predict Output
intermediate
2:00remaining
What error does this code raise when accessing a double underscore attribute?
What happens if you try to access a double underscore attribute directly without name mangling?
Python
class Test:
    def __init__(self):
        self.__secret = 'hidden'

obj = Test()
print(obj.__secret)
AAttributeError
BSyntaxError
C'hidden'
DTypeError
Attempts:
2 left
💡 Hint
Double underscore attributes are renamed internally, so direct access fails.
🧠 Conceptual
advanced
2:00remaining
Why does Python use name mangling for double underscore attributes?
Choose the best explanation for why Python applies name mangling to attributes starting with double underscores.
ATo prevent accidental access and name clashes in subclasses
BTo make attributes private and inaccessible everywhere
CTo optimize attribute lookup speed
DTo allow attributes to be accessed without self prefix
Attempts:
2 left
💡 Hint
Think about inheritance and attribute name conflicts.
Predict Output
advanced
2:00remaining
What is the output of this code with inheritance and name mangling?
Given these classes, what will be printed?
Python
class Base:
    def __init__(self):
        self.__value = 'Base'

class Derived(Base):
    def __init__(self):
        super().__init__()
        self.__value = 'Derived'

obj = Derived()
print(obj._Base__value)
print(obj._Derived__value)
ADerived\nBase
BBase\nDerived
CAttributeError
DBase\nBase
Attempts:
2 left
💡 Hint
Each class has its own mangled attribute name.
🔧 Debug
expert
2:00remaining
Why does this code fail to update the intended attribute?
This code tries to update a double underscore attribute in a subclass but fails. Why?
Python
class Parent:
    def __init__(self):
        self.__data = 10

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.__data = 20

obj = Child()
print(obj._Parent__data)
AAttributeError because _Parent__data does not exist
BIt prints 20 because Child overrides Parent's attribute
CIt prints 10 because Child's __data is a different mangled attribute
DSyntaxError due to double underscores
Attempts:
2 left
💡 Hint
Remember that name mangling depends on the class where the attribute is defined.

Practice

(1/5)
1. What does name mangling do to an attribute starting with double underscores in a Python class?
easy
A. It adds the class name before the attribute name to avoid conflicts.
B. It makes the attribute public and accessible everywhere.
C. It deletes the attribute from the class.
D. It converts the attribute name to uppercase.

Solution

  1. Step 1: Understand double underscore prefix

    Attributes starting with double underscores trigger name mangling in Python classes.
  2. Step 2: Effect of name mangling

    Python adds the class name before the attribute name to avoid accidental access or conflicts.
  3. Final Answer:

    It adds the class name before the attribute name to avoid conflicts. -> Option A
  4. Quick 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
A. self.__my_attr = 5
B. def __my_attr(self): pass
C. self._my_attr = 5
D. self.my_attr__ = 5

Solution

  1. Step 1: Identify private attribute syntax

    Private attributes use double underscores at the start of the name, like __my_attr.
  2. Step 2: Check correct assignment

    Assigning with self.__my_attr = 5 correctly defines a private attribute with name mangling.
  3. Final Answer:

    self.__my_attr = 5 -> Option A
  4. Quick 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
A. True\nTrue
B. False\nTrue
C. True\nFalse
D. False\nFalse

Solution

  1. Step 1: Check attribute __x existence

    Due to name mangling, __x is stored as _A__x internally, so hasattr(a, '__x') returns False.
  2. Step 2: Check mangled attribute _A__x existence

    hasattr(a, '_A__x') returns True because this is the mangled name storing the value.
  3. Final Answer:

    False True -> Option B
  4. Quick 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
A. SyntaxError due to double underscores
B. No error, prints 5
C. TypeError because __val is private
D. AttributeError because __val is name mangled

Solution

  1. Step 1: Understand name mangling effect

    __val is mangled to _B__val internally, so b.__val does not exist.
  2. Step 2: Accessing __val causes AttributeError

    Trying to print b.__val raises AttributeError because the attribute is hidden by name mangling.
  3. Final Answer:

    AttributeError because __val is name mangled -> Option D
  4. Quick 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:
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
A. c.__data
B. c._data
C. c._C__data
D. c.get_data()

Solution

  1. Step 1: Understand name mangling for __data

    The attribute __data is stored internally as _C__data due to name mangling.
  2. Step 2: Access mangled attribute directly

    You can access it from outside the class using c._C__data.
  3. Final Answer:

    c._C__data -> Option C
  4. Quick 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