0
0
Pythonprogramming~10 mins

Private attributes 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 define a private attribute named __value in the class.

Python
class MyClass:
    def __init__(self, val):
        self.[1] = val
Drag options to blanks, or click blank then click option'
Avalue
B__value
C_value
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single underscore instead of double underscores.
Not using underscores at all.
Using the parameter name directly as attribute.
2fill in blank
medium

Complete the code to access the private attribute __value inside the class method.

Python
class MyClass:
    def __init__(self, val):
        self.__value = val
    def get_value(self):
        return self.[1]
Drag options to blanks, or click blank then click option'
A__value
B_value
Cvalue
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single underscore instead of double underscores.
Trying to access the attribute without underscores.
3fill in blank
hard

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

Python
obj = MyClass(10)
print(obj.[1])
Drag options to blanks, or click blank then click option'
A__value
Bvalue
C_MyClass__value
D_value
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access the attribute with just double underscores.
Using the attribute name without underscores.
4fill in blank
hard

Fill both blanks to create a private attribute and a method to access it.

Python
class Data:
    def __init__(self, val):
        self.[1] = val
    def get_val(self):
        return self.[2]
Drag options to blanks, or click blank then click option'
A__secret
Bsecret
D_secret
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for attribute and access.
Using single underscore instead of double.
5fill in blank
hard

Fill all three blanks to define a private attribute, a getter method, and access the private attribute outside the class using name mangling.

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

obj = Secret(42)
print(obj.[3])
Drag options to blanks, or click blank then click option'
A__data
C_Secret__data
D_data
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access private attribute outside class with just double underscores.
Using inconsistent attribute names.