Getter and setter methods let you safely read and change values inside an object. They help keep data correct and private.
When you want to control how a value is read or changed in an object.
When you want to check or change data before saving it.
When you want to hide the details of how data is stored inside an object.
When you want to add extra actions when a value changes, like updating another value.
When you want to prevent direct access to important data to avoid mistakes.
Syntax
Python
class ClassName:
def __init__(self, value):
self._attribute = value
def get_attribute(self):
return self._attribute
def set_attribute(self, new_value):
self._attribute = new_value
Use a single underscore (_) before attribute names to show they are 'private' by convention.
Getter methods start with get_ and setter methods start with set_.
Examples
Simple getter and setter for a person's name.
Python
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
def set_name(self, new_name):
self._name = new_name
Setter checks if temperature is above absolute zero before setting.
Python
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
def get_celsius(self):
return self._celsius
def set_celsius(self, temp):
if temp < -273.15:
print('Temperature too low!')
else:
self._celsius = temp
Sample Program
This program creates a bank account with a balance. It uses getter and setter to read and update the balance safely. It prevents setting a negative balance.
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?