Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Using Getter and Setter Methods in Python
📖 Scenario: You are creating a simple program to manage a person's age. You want to control how the age is accessed and changed to keep it valid.
🎯 Goal: Build a Python class called Person that uses getter and setter methods to safely access and update the age attribute.
📋 What You'll Learn
Create a class named Person with a private attribute _age.
Add a getter method called get_age to return the current age.
Add a setter method called set_age to update the age only if the new value is between 0 and 120.
Create an instance of Person and set the age using the setter.
Print the age using the getter.
💡 Why This Matters
🌍 Real World
Getter and setter methods are used in many programs to protect important data and make sure it stays correct.
💼 Career
Understanding how to control access to data is important for writing safe and reliable software, a key skill for any programmer.
Progress0 / 4 steps
1
Create the Person class with a private age attribute
Create a class called Person with an __init__ method that sets a private attribute _age to 0.
Python
Hint
Use self._age = 0 inside the __init__ method to create the private attribute.
2
Add getter and setter methods for age
Add a method called get_age that returns self._age. Add another method called set_age that takes a parameter new_age and sets self._age to new_age only if it is between 0 and 120.
Python
Hint
The getter returns self._age. The setter checks if new_age is between 0 and 120 before setting self._age.
3
Create a Person instance and set the age
Create an instance of Person called person. Use the set_age method to set the age to 25.
Python
Hint
Create the object with person = Person() and set age with person.set_age(25).
4
Print the age using the getter method
Use print to display the age by calling person.get_age().
Python
Hint
Use print(person.get_age()) to show the age.
Practice
(1/5)
1. What is the main purpose of getter and setter methods in a Python class?
easy
A. To create new classes dynamically
B. To control access to private attributes safely
C. To execute code asynchronously
D. To delete objects from memory
Solution
Step 1: Understand getter and setter roles
Getter methods retrieve attribute values, and setter methods update them while controlling access.
Step 2: Identify their purpose in encapsulation
They protect private data by allowing controlled reading and writing, preventing direct access.
Final Answer:
To control access to private attributes safely -> Option B
Quick Check:
Getter/setter = control private data [OK]
Hint: Getters and setters manage private data access [OK]
Common Mistakes:
Thinking they create new classes
Confusing with asynchronous code
Assuming they delete objects
2. Which of the following is the correct syntax to define a setter method for attribute age using the @property decorator in Python?
easy
A. @property.setter\ndef set_age(self, value):\n self._age = value
B. @setter.age\ndef age(self, value):\n self._age = value
C. @age.setter\ndef age(self, value):\n self._age = value
D. @age.setter\ndef set_age(self):\n self._age = value
Solution
Step 1: Recall setter syntax with @property
The setter uses @attribute.setter decorator and method name matches the attribute.
Step 2: Check method signature
Setter method takes self and value parameters to set the attribute.
Final Answer:
@age.setter\ndef age(self, value):\n self._age = value -> Option C
Quick Check:
Setter uses @age.setter and method age(self, value) [OK]
Hint: Setter uses @attribute.setter and method named attribute [OK]
Common Mistakes:
Using wrong decorator like @setter.age
Method name not matching attribute
Setter missing value parameter
3. What will be the output of the following code?
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value.upper()
p = Person('alice')
p.name = 'bob'
print(p.name)
medium
A. bob
B. Error
C. alice
D. BOB
Solution
Step 1: Understand setter behavior
Setter converts the assigned value to uppercase before storing it.
Step 2: Trace code execution
Initially name is 'alice', then set to 'bob' which setter changes to 'BOB'. Printing returns 'BOB'.
Final Answer:
BOB -> Option D
Quick Check:
Setter uppercases value, output = BOB [OK]
Hint: Setter modifies value before storing, output reflects change [OK]
Common Mistakes:
Expecting original lowercase 'bob'
Thinking print shows initial 'alice'
Assuming code raises error
4. Identify the error in this code snippet using getter and setter methods:
Setter must accept two parameters: self and value to set the attribute.
Step 2: Identify missing parameter
Current setter only has self, missing value parameter, causing error on assignment.
Final Answer:
Setter method missing value parameter -> Option A
Quick Check:
Setter needs (self, value) parameters [OK]
Hint: Setter must have value parameter besides self [OK]
Common Mistakes:
Omitting value parameter in setter
Confusing getter and setter decorators
Assuming code runs without error
5. You want to create a class Temperature that stores temperature in Celsius internally but allows getting and setting the temperature in Fahrenheit using getter and setter methods. Which code correctly implements this behavior?