0
0
Pythonprogramming~10 mins

Getter and setter methods 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 getter method for the attribute 'name'.

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

    def get_name(self):
        return self.[1]
Drag options to blanks, or click blank then click option'
A_name
Bname
Cself._name
Dself.name
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 'name' instead of '_name'.
Including 'self' again inside the return statement.
2fill in blank
medium

Complete the code to define a setter method for the attribute 'age'.

Python
class Person:
    def __init__(self, age):
        self._age = age

    def set_age(self, age):
        self.[1] = age
Drag options to blanks, or click blank then click option'
Aself._age
Bself.age
Cage
D_age
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to 'age' instead of '_age'.
Writing 'self.self._age' by mistake.
3fill in blank
hard

Fix the error in the setter method to correctly update the private attribute '_salary'.

Python
class Employee:
    def __init__(self, salary):
        self._salary = salary

    def set_salary(self, salary):
        [1] = salary
Drag options to blanks, or click blank then click option'
Aself._salary
B_salary
Csalary
Dself.salary
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to '_salary' without 'self.', which does not update the attribute.
Assigning to 'salary' which is just the parameter.
4fill in blank
hard

Fill both blanks to create a property for 'height' with getter and setter methods.

Python
class Person:
    def __init__(self, height):
        self._height = height

    @property
    def height(self):
        return self.[1]

    @height.setter
    def height(self, value):
        self.[2] = value
Drag options to blanks, or click blank then click option'
A_height
Bheight
Dheight_value
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'height' instead of '_height' in getter or setter.
Using different names in getter and setter.
5fill in blank
hard

Fill all three blanks to create a property 'weight' with getter, setter, and a condition to allow only positive values.

Python
class Person:
    def __init__(self, weight):
        self._weight = weight

    @property
    def weight(self):
        return self.[1]

    @weight.setter
    def weight(self, value):
        if value [2] 0:
            self.[3] = value
Drag options to blanks, or click blank then click option'
A_weight
B>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the condition.
Assigning to 'weight' instead of '_weight'.