0
0
Pythonprogramming~20 mins

Name mangling in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.