0
0
Pythonprogramming~10 mins

Name mangling in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to access the mangled private variable inside the class.

Python
class MyClass:
    def __init__(self):
        self.__secret = 42

obj = MyClass()
print(obj.[1])
Drag options to blanks, or click blank then click option'
Asecret
B__secret
C_MyClass__secret
D_secret
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access __secret directly causes an AttributeError.
Using _secret or secret does not match the mangled name.
2fill in blank
medium

Complete the code to define a method that accesses the mangled private variable.

Python
class SecretHolder:
    def __init__(self):
        self.__hidden = 'safe'
    def reveal(self):
        return self.[1]
Drag options to blanks, or click blank then click option'
A_SecretHolder__hidden
B__hidden
C_hidden
Dhidden
Attempts:
3 left
💡 Hint
Common Mistakes
Using __hidden directly inside the method.
Using _hidden or hidden which are not the mangled names.
3fill in blank
hard

Fix the error in accessing the private variable from outside the class.

Python
class Data:
    def __init__(self):
        self.__value = 100

obj = Data()
print(obj.[1])
Drag options to blanks, or click blank then click option'
A__value
B_Data__value
C_value
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access __value directly causes AttributeError.
Using _value or value does not match the mangled name.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps attribute names to their mangled values.

Python
class Info:
    def __init__(self):
        self.__a = 1
        self.__b = 2

obj = Info()
attrs = {name: getattr(obj, [1]) for name in ['a', 'b'] if hasattr(obj, [2])}
Drag options to blanks, or click blank then click option'
A'_Info__' + name
B'__' + name
C'_' + name
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using '__' + name misses the class name prefix.
Using '_' + name or just name does not match mangled names.
5fill in blank
hard

Fill all three blanks to define a class with a private variable, a method to access it, and external access using name mangling.

Python
class Secret:
    def __init__(self, val):
        self.[1] = val
    def get_secret(self):
        return self.[2]

s = Secret('hidden')
print(s.[3])
Drag options to blanks, or click blank then click option'
A__data
B_Secret__data
D__secret
Attempts:
3 left
💡 Hint
Common Mistakes
Using __secret instead of __data.
Accessing the variable outside the class without mangling.