Getters and Setters in Python. Topic – 43

Getters and Setters in python

Today in this post we will learn about getters and setters in Python. Getters and setters is a concept that will help us to encapsulate the data. In the previous post, we already read what is data encapsulation.

In OOPs languages, getters and setters are used to retrieve and update data. A getter retrieves an object’s current attribute value, whereas a setter changes an object’s attribute value. Getters and setters concept is a little bit tricky. You may think this is difficult but not like that. It needs some practice to understand this concept. Before understanding this concept you must have knowledge about these topics that I already posted before:

  • Function in Python
  • Class and Objects in Python
  • Introduction to OOPs in Python
  • Class & Objects In Python
  • Constructor in Python. Topic
  • Decorators in Python. Topic

 So if you are familiar with this content you can go ahead. Otherwise, you can’t understand this concept. Let’s see through the code.

Example 1 :

Imagine a Student class to manage a student’s information. We’ll use getters and setters to access and modify the student’s name.

Step – 1:

Python
class Students:
    def __init__(self, name):
        self._name = name

First, we created a class named “Student”. Inside this class, we created an __init__ function that allows us to initialize all the values. And it is mandatory to pass self to the __init__ method. And we are passing 2 parameters, name, which will store the student’s name.

Step – 2:

Python
self._name = name

Now the question is why did we do this? What does it mean? It means that we are telling the name variable that whatever value it receives (through the value argument), it will store it in the _name variable. And it is necessary to put self in the init method, so it is self._name. There is another question here: what is the first underscore (_) doing in _name? This underscore is the same thing that encapsulates a variable.

Step – 3

Python
def get_name(self):
  return self._name

Now we are creating a method inside that class. And the job of this method will be to get the name of the student. And it is necessary to put "get" before the name of this method. This is the rule for applying the getter method. We will discuss this later. For now, just understand that if you put get, it means you are applying the getter method.

So, always remember that getters methods are used to get values. And setters methods are those methods that help update a value.

Suppose we have a value: password = “@123Python”. So, if we want to change the value of the password, we can do it like this: password = “@123javascript”. But if we want no one to be able to change this value, we use the getter method. And to update that value, we write a separate method which we call the setters method. This means that we write the method to update that value in the setters method. So, now go to step – 4:

Step – 4

Python
def set_name(self, new_name):
    if len(new_name) >= 4:
        self._name = new_name
        print("Name updated...")

    else:
        print("Name should be 4 letter or above")

We have taken a method named set_name. And you know that it is necessary to put set before. And we have passed a parameter named “new_name” which will store the value of our updated name.

Then we have put a simple if-else and checked that if the name is 4 letters or more, then set the value of “self._name” to “new_name”. If the condition is false, which means the name is less than 4 letters, then we cannot update the value.

Step – 5:

Python
# Create a Student object
elem1 = Students("Arpan")
print(elem1._name)

So what did we do in this line? To understand this line, you need to have the concept of classes and objects. If you don’t understand, read about classes and objects once. Basically, we created an object of the “Students” class and stored it in elem1. Then we accessed .self_name from elem1.

In addition to the value we printed above, there is another efficient way. We can use the getter method (get_name) to access the value. So let’s see how it is done.

Python
elem1 = Students("Arpan")
res = elem1.get_name()  #print(elem1.get_name())
print(res)

So now if you want to change the name and set it to something else. Then to update that value, you will need the setter method that we have already created. So let’s see in the code.

Python
elem1.set_name("Ritwika")
print(elem1.get_name())

So we can update the value like this.

Let’s review what we’ve done in this entire program:

Python
class Students:
    def __init__(self, name): # Name is parameter
        self._name = name # Using _ before an attribute makes it private

    def get_name(self):
        return self._name
    
    def set_name(self, new_name): 
         # Validation logic
        if len(new_name) >= 4: 
            self._name = new_name
            print("Name updated...")

        else:
            print("Name should be 4 letter or above")

# Print the value
elem1 = Students("Arpan")
print(elem1.get_name())

# Print the vale using getter method 
elem1 = Students("Arpan")
res = elem1.get_name()  #print(elem1.get_name())
print(res)

# Update the vale using setter method 
elem1.set_name("Ritwika")
print(elem1.get_name())
Getters and Setters in Python

So we have seen the basic method. Getters and setters are used in this way. But we can also do this with the property decorator. Both work the same way, but it becomes easier to do this way. Let’s see that too once. Because of most of the good developers use it.

Python
class Students:
    def __init__(self, name): # Name is parameter
        self._name = name # Using _ before an attribute makes it private

    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, new_name): 
         # Validation logic
        if len(new_name) >= 4: 
            self._name = new_name
            print("Name updated...")

        else:
            print("Name should be 4 letter or above")

# before update the value
elem1 = Students("Priti")
print(elem1.name)

# Use setter for validation
elem1.name = "Ritwika"
print(elem1.name)

# If name is less than 4 letter
elem1.name = "Rit"
print(elem1.name)

@property Decorator:

  • Replaces the get_name and get_marks methods with properties.
  • Provides a clean way to access private attributes (_name and _marks) as if they were public attributes without directly exposing them.
  • The @property decorator defines a getter method that retrieves the value.

@name.setter Decorator:

  •     Replace the set_name and set_marks methods with setters.
  •     Allows you to control how values are assigned to the properties (name and marks).
  •     The @name.setter decorator defines a setter method that validates and sets the value.
Decorators in Python

Decorators in Python

Today in this content we will learn about the decorators in Python. They provide a clean and concise way to add functionality to …

I hope you understand “Getters and Setters in Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog