0
0
Pythonprogramming~30 mins

Getter and setter methods in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use print(person.get_age()) to show the age.