Published Aug. 29, 2023, 1:08 a.m.
Python classes offer us some handy tools called setter and getter methods. These methods allow us to control how data is assigned and accessed in a smart way, ensuring everything is tidy and safe.
Suppose you have a box (an instance variable) where you want to store something. The setter method is like a security guard for this box. It verifies what you're trying to store and makes sure it's the right thing. If it's not, the guard will stop it.
How to Use a Setter Method:
def setVariable(self, value):
self.variable = value
Example:
Let's say we want to manage a person's age. We can use a setter method like this:
class Person:
def setAge(self, age):
if age >= 0:
self.age = age # Set the age if it's non-negative
else:
print("Age cannot be negative.")
This setter method helps us keep ages positive and regulated.
Now, think of the box again. You might want to see inside, but you don't want to disturb what's inside. The getter method acts like a glass to look inside the box without changing anything.
How to Use a Getter Method:
def getVariable(self):
return self.variable
Example:
Let's talk about a bank account balance. You want to know how much money you have, but you don't want to accidentally add or remove any money. That's where a getter method comes in:
class BankAccount:
def __init__(self, balance):
self.balance = balance
def getBalance(self):
return self.balance # Return the balance when asked
This getter method gives you a way to check your balance without risking any changes.
# Creating a Person object
person = Person()
person.setAge(25) # Using the setter method to set age
print(person.age) # Checking the age directly (not the best idea)
# Creating a BankAccount object
account = BankAccount(1000)
print(account.getBalance()) # Using the getter method to check balance
Output:
25
1000
Setter and getter methods are like protectors for your data in Python classes. They help you assign and access values in a controlled way, making sure everything is neat, organized, and secure. By using these methods, you keep your code clean and clear while making sure your data stays in good shape.
Example that demonstrates the use of setter and getter methods in a class representing a Book.
We'll create a Book
class with attributes title
, author
, and price
. We'll use setter methods to ensure proper validation while setting values for these attributes, and getter methods to retrieve these values.
class Book:
def setTitle(self, title):
self.title = title # Set the book's title
def setAuthor(self, author):
self.author = author # Set the author's name
def setPrice(self, price):
if price > 0:
self.price = price # Set the book's price if it's positive
else:
print("Price must be a positive value.")
def getTitle(self):
return self.title # Get the book's title
def getAuthor(self):
return self.author # Get the author's name
def getPrice(self):
return self.price # Get the book's price
# Creating a Book object
book1 = Book()
# Using setter methods to set values
book1.setTitle("The Great Gatsby")
book1.setAuthor("F. Scott Fitzgerald")
book1.setPrice(15.99)
# Using getter methods to retrieve values
print("Book Title:", book1.getTitle())
print("Author:", book1.getAuthor())
print("Price:", book1.getPrice())
Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: 15.99
Book
class with setter and getter methods for title
, author
, and price
.setTitle
, setAuthor
, setPrice
) ensure that the provided values are properly assigned to the instance variables, with necessary validations for the price
attribute.getTitle
, getAuthor
, getPrice
) allow us to retrieve the values of the attributes without directly accessing them.Book
object named book1
.This example illustrates how setter and getter methods maintain controlled access to instance variables, enabling us to ensure data integrity and encapsulation.