Getter and Setter in Python
In this tutorial, we’ll discuss getter and setter methods in Python, understanding what they are, why they are crucial, and how to implement them effectively.
When we define a class in Python, we may need to define private data attributes that we can’t access directly from the outside the class.
In this case, it is a good programming practice to control the access to data attributes through two special types of methods, commonly known as getter and setter. Many OOP languages, such as Java, use such methods to implement the concept of data encapsulation.
A method which is used to retrieve / get / read the value of private instance attribute (i.e. instance variable) is called getter method in Python. This method is also known as accessor method in Python.
For every private instance attribute that you want to access from outside the class, it’s a good practice to create a corresponding getter method.
A method which is used to update / modify / set the value of private instance attribute is called setter method in Python. This method is also known as mutator method in Python.
By using the setter method, we can modify or update the value of a variable in Python. Just like the getter method, it is a common and good practice to create a setter method for every private variable in a class that you want to set the value of from outside the class.
Thus, the setter method is used to store the data into private instance variables whereas, getter method is used to read that data.
How to Implement Getter and Setter Method in Python?
Let’s take a simple example program in which we will understand how to implement getter and setter method in Python program. If we define both getter and setter methods for the private instance attributes (variables with name starting with an underscore, like __private_variable) in the class, we can make them both read-write. Look at the below example step by step.
Example 1:
# Define a class.
class Student:
# Define the getter method to read private attribute __name.
def get_name(self):
return self.__name
# Define the setter method to write or set the value of private attribute __name.
def set_name(self, name):
self.__name = name
# Outside the class definition.
# Create an instance of class Student.
st = Student()
# Call the setter method to set the value of private attribute.
st.set_name("Deepak")
# Call the getter method to read the value of private attribute.
result = st.get_name()
print("Name: ", result)
Output:
Name: Deepak
In this example, we have defined a class named Student that contains getter and setter methods. The getter method get_name reads the value of private attribute (i.e. variable) __name and returns the value to the method call. This getter method also takes the self parameter that denotes the reference to the current object being used.
The setter method store data or value in the private attribute __name of the object. As the data attribute is private, it is only accessible using getter and setter methods within the class. In Python or any other programming languages, you should define getter and setter methods for all private instance variables defined in the class.
In other words, for every private instance variable, you should define the associated getter and setter methods within the class. In this context, if we try to access the private instance attribute directly, an error will take place. Thus, we have performed both read and write operations in this Python program using getter and setter methods.
Let’s take an advanced example program in which we will use a constructor method to initialize the private instance variables, as well as getter and setter methods to read and update the values for each private variable.
Example 2:
# Define a class.
class Employee:
# Define a constructor method to initialize private instance variables.
def __init__(self, name, salary):
self.__name = name
self.__salary = salary
# Define getter methods to read the value of each private attribute.
def get_name(self):
return self.__name
def get_salary(self):
return self.__salary
# Define setter methods to set the value of each private attribute.
def set_name(self, name):
self.__name = name
def set_salary(self, salary):
self.__salary = salary
# Outside the class definition.
# Create an instance of class Employee.
emp = Employee("Tripti", 120000)
# Call getter methods to read the value of each private attribute.
emp_name = emp.get_name()
emp_salary = emp.get_salary()
print("Employee name: ", emp_name)
print("Employee salary: ", emp_salary)
# Call the setter methods to set the new value for each private attribute.
emp.set_name("Deepak")
emp.set_salary(50000)
# Call getter methods to read the new value of each private attribute.
emp_name = emp.get_name()
emp_salary = emp.get_salary()
print("Employee name: ", emp_name)
print("Employee salary: ", emp_salary)
Output:
Employee name: Tripti
Employee salary: 120000
Employee name: Deepak
Employee salary: 50000
Creating Read-Only and Write-Only Attributes
In the previous example programs, we have used getter and setter methods to perform both read and write operations. However, we may also use getter or setter method to perform read only or write only operation. If we define only the getter method for the private instance attribute in the class, we make it read-only.
While, if we define only the setter method for the private instance attribute in the class, we make it write-only. Let’s take simple example programs based on both read-only and write-only operation.
Example 3:
# Define a class.
class Employee:
# Define getter and setter methods for the first name.
def get_first_name(self):
return self.__firstName
def set_first_name(self, fName):
self.__firstName = fName
# Define getter and setter methods for the last name.
def get_last_name(self):
return self.__lastName
def set_last_name(self, lName):
self.__lastName = lName
# Define getter methods for read-only attributes.
def get_email(self):
email = self.__firstName + "." +self.__lastName + "@scientecheasy.com"
return email
def get_full_name(self):
full_name = self.__firstName + " " + self.__lastName
return full_name
# Outside the class definition.
# Create an instance of class Employee.
emp = Employee()
# Call the setter methods to store the value to private instance attributes.
emp.set_first_name("Tripti")
emp.set_last_name("Priya")
# Call getter methods to print read-only attributes.
print("Full name: ", emp.get_full_name())
print("Email id: ", emp.get_email())
Output:
Full name: Tripti Priya
Email id: Tripti.Priya@scientecheasy.com
In this example, we have defined a class named Employee that contains private instance attributes for employee’s first and last names, and the corresponding getter and setter methods. This class also contains attributes for the employee’s emails and full names.
These attributes are read-only attributes, which do not have setter methods. Then, we have created an instance of class Employee and called setter methods by passing values to the private instance attributes. After that, we have called getter methods to print read-only attributes.
Let’s take an example program in which we will define only the setter methods to store values into the private attributes and make them write only. Here, we will calculate the sum of three numbers and display it on the console.
Example 4:
class Addition:
def set_x(self, x):
self.__x = x
def set_y(self, y):
self.__y = y
def set_z(self, z):
self.__z = z
def sum(self):
s = self.__x + self.__y + self.__z
print("Sum of three numbers: ", s)
# Create an instance of class Addition.
obj = Addition()
# Calling setter methods to set values of private variables.
obj.set_x(20)
obj.set_y(30)
obj.set_z(50)
obj.sum()
Output:
Sum of three numbers: 100
Validating Inputs before Setting
As we have discussed, getter and setter methods are commonly used to access and manipulate the data values of private instance attributes or variables in Python. In addition, they also offer the functionality of data input validation before setting. Let’s take an example based on it.
Example 5:
# Define a class.
class Employee:
# Define a setter method for private attribute '__firstName'.
def set_firstName(self, name):
# Check the characters of attribute name and store it if it is lower than 15 characters.
if len(name) < 15:
self.__firstName = name
# Define a getter method for private attribute '__firstName'.
def get_firstName(self):
return self.__firstName
# Define a setter method for private attribute '__salary'.
def set_salary(self, salary):
# Check attribute salary and store it if it is between 0 and 50000.
if (salary > 0 and salary < 50000):
self.__salary = salary
# Define getter method for private attribute '__salary'.
def get_salary(self):
return self.__salary
# Create an instance of Employee.
emp = Employee()
# Call setter methods to validate and store in its attributes.
emp.set_firstName("Deepak")
emp.set_salary(40000)
# Call getter method to print the stored values and associated messages.
print("Name of employee: ", emp.get_firstName())
print("Salary: ", emp.get_salary())Output:
Name of employee: Deepak
Salary: 40000
In this example, we have defined a class named Employee. This class contains two setter methods (set_firstName and set_salary). These methods are responsible for setting the values of private attributes.
The set_firstName method takes a parameter name and sets the __firstName attribute if the length of name is less than 15 characters.
The set_salary method takes a parameter salary and sets the __salary attribute if the salary is greater than 0 and less than 50000.
Similarly, there are two getter methods (get_firstName and get_salary) in the Employee class. The get_firstName method returns the value of the __firstName attribute. The get_salary method returns the value of the __salary attribute.
Then, we have created an instance of the Employee class and assigned to the variable emp. We have called setter methods to set values “Deepak” and 40000 to private attributes ‘__firstName’ and ‘__salary’.
Finally, we have called getter methods to print employee’s name and salary. Thus, we have performed data input validation before setting into private attributes in this example.
Advantage of Getter and Setter Methods in Python
There are the following advantages of using getter and setter methods in Python. They are as:
- Getter and setter methods allow us to validate data input when reading (getting) or writing (setting) attribute values.
- With getter and setter, we can set different access levels (e.g., public, protected, private) for the instance attributes in the class.
- They prevent direct access and manipulation of the data attribute.
In this tutorial, we have discussed getter and setter methods in Python that are valuable role in data validation, access control, and preventing direct access to instance attributes. Hope that you will have understood how to implement getter and setter for the instance attributes and practiced all example programs. In the next, we will get the complete knowledge of data hiding in Python with the help of advanced example programs.
Thanks for reading!!!

