0
0
Pythonprogramming~10 mins

Purpose of encapsulation 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 class with a private attribute.

Python
class Person:
    def __init__(self, name):
        self.[1]name = name
Drag options to blanks, or click blank then click option'
A_
Bpublic_
C__
Dprivate_
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single underscore instead of double underscores.
Using 'public_' or 'private_' as prefixes which are not valid in Python.
2fill in blank
medium

Complete the method to access the private attribute safely.

Python
class Person:
    def __init__(self, name):
        self.__name = name
    def get_name(self):
        return self.[1]name
Drag options to blanks, or click blank then click option'
A__
B_Person__
C_
Dpublic_
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access __name directly without name mangling.
Using single underscore instead of name mangling.
3fill in blank
hard

Fix the error in the setter method to update the private attribute.

Python
class Person:
    def __init__(self, name):
        self.__name = name
    def set_name(self, name):
        self.[1]name = name
Drag options to blanks, or click blank then click option'
A__name
B_name
Cname
Dself.name
Attempts:
3 left
💡 Hint
Common Mistakes
Using a public attribute name instead of the private one.
Using single underscore or no underscore.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that stores private attribute lengths for names longer than 3.

Python
class Person:
    def __init__(self, name):
        self.__name = name

names = [Person('Anna'), Person('Bob'), Person('Catherine')]
lengths = {person.[1]name: len(person.[2]name) for person in names if len(person._Person__name) > 3}
Drag options to blanks, or click blank then click option'
A_Person__
B__
Cname
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using __name or name directly outside the class.
Using single underscore or self which are invalid here.
5fill in blank
hard

Fill all three blanks to create a method that safely updates the private attribute only if the new name is longer than 2 characters.

Python
class Person:
    def __init__(self, name):
        self.__name = name
    def update_name(self, new_name):
        if len(new_name) > [1]:
            self.[2]name = new_name
            return True
        else:
            return [3]
Drag options to blanks, or click blank then click option'
A3
B__
CFalse
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong length number in the condition.
Using single underscore or no underscore for private attribute.
Returning True instead of False when condition fails.