0
0
Pythonprogramming~10 mins

Protected 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 protected 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'
A__value
Bvalue
C_value
Dvalue_
Attempts:
3 left
💡 Hint
Common Mistakes
Using no underscore or double underscore for protected attributes.
2fill in blank
medium

Complete the code to access the protected attribute _value inside a method of the class.

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'
Avalue
B_value
C__value
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access the attribute without the underscore or with double underscores.
3fill in blank
hard

Fix the error in accessing the protected 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
Cval
D_value
Attempts:
3 left
💡 Hint
Common Mistakes
Using double underscores or no underscore when accessing the attribute.
4fill in blank
hard

Fill both blanks to create a subclass that accesses the protected attribute of its parent class.

Python
class Parent:
    def __init__(self):
        self._value = 5

class Child(Parent):
    def show_value(self):
        return [1].[2]
Drag options to blanks, or click blank then click option'
Aself
BParent
C_value
D__value
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access the attribute via the class name or using double underscores.
5fill in blank
hard

Fill all three blanks to define a class with a protected attribute, a method to set it, and a method to get it.

Python
class Data:
    def __init__(self):
        self.[1] = None
    def set_value(self, val):
        self.[2] = val
    def get_value(self):
        return self.[3]
Drag options to blanks, or click blank then click option'
A_data
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names or missing the underscore in some places.