What is Setter() in Python?
Setters are methods in OOPs that are used to modify and update the value of an attribute of an object. Certain constraints can also be applied along with setter methods. This ensures that the new values assigned to the attributes are valid. Setter() are used together with the getter() method in Python.
Implementing Getter and Setter in Python
1. Using the Normal Function
In the example below, we used the getter method to get the value of total marks and total subjects and then used the setter method to set their values to 450 and 5, respectively. After this, we retrieved the values of the above attributes to calculate the student's average marks.
Python
class Ninja:
def __init__(self, totalMarks = 0, totalSub=0):
self._totalMarks = totalMarks
self._totalSub = totalSub
# getter method
def get_totalMarks(self):
return self._totalMarks
# setter method
def set_totalMarks(self, x):
self._totalMarks = x
# getter method
def get_totalSub(self):
return self._totalSub
# setter method
def set_totalSub(self, y):
self._totalSub = y
student = Ninja()
# Setting the totalMarks using setter
student.set_totalMarks(450)
# setting the totalSub using setter
student.set_totalSub(5)
# retrieving totalMarks using getter
print("Total Marks:" + str(student.get_totalMarks()))
# retrieving totalSub using getter
print("Total Sub:" + str(student.get_totalSub()))
# calculate average
print("Average:" + str(student._totalMarks/student._totalSub))
You can also try this code with Online Python Compiler
Run Code
Output:
Total Marks:450
Total Sub:5
Average:90.0
You can also try this code with Online Python Compiler
Run Code2. Using the property() function
Python's property() function is a built-in function that allows programmers to create properties with getter and setter behaviour. The property() function takes three arguments: the getter function, the setter function, and the delete function (optional).
In the below example, we have used the property() function to achieve the getter and setter behaviour in Python.
Python
class Ninja:
def __init__(self):
self._totalMarks = 0
self._totalSub = 0
# using the get function
def get_totalMarks(self):
print("getter method")
return self._totalMarks
# Using the set function
def set_totalMarks(self, y):
print("setter method")
self._totalMarks = y
# using the del function
def del_totalMarks(self):
del self._totalMarks
totalMarks = property(get_totalMarks, set_totalMarks, del_totalMarks)
def get_totalSub(self):
print("getter method")
return self._totalSub
# Using the set function
def set_totalSub(self, z):
print("setter method")
self._totalSub = z
# using the del function
def del_totalSub(self):
del self._totalSub
totalSub = property(get_totalSub, set_totalSub, del_totalSub)
student = Ninja()
student.totalMarks = 450
student.totalSub = 5
print(student.totalMarks/student.totalSub)
You can also try this code with Online Python Compiler
Run Code
Output:
setter method
setter method
getter method
getter method
90.0
You can also try this code with Online Python Compiler
Run Code3. Using the @property decorators
Getter and Setter methods in Python can also be implemented using the @property decorators. The @property decorator helps the programmer to create properties that behave like attributes but provide flexibility to validate the values assigned to them.
In the below example, we have used the @property decorator to achieve the getter and setter behaviour in Python.
Python
class Ninja:
def __init__(self):
self._totalMarks = 0
self._totalSub = 0
@property
# using the get function
def totalMarks(self):
print("getter method")
return self._totalMarks
@totalMarks.setter
# Using the set function
def totalMarks(self, y):
if(y < 200):
raise ValueError("Student has failed the exam")
print("setter method")
self._totalMarks = y
student = Ninja()
student.totalMarks = 420
student.totalSub = 5
print(student.totalMarks/student.totalSub)
You can also try this code with Online Python Compiler
Run Code
Output:
setter method
getter method
84.0
You can also try this code with Online Python Compiler
Run CodeThe above example gives a valueError if we initialise the value of totalMarks < 200, thus serving as a check constraint on totalMarks.
Making the Attributes Private
In Python, you can make attributes private by prefixing them with double underscores (e.g., `__attribute`). This name-mangling technique encapsulates the attribute, making it less accessible from outside the class, thus improving data security and preventing unintended modifications or direct access.
Example
Python
class MyClass:
def __init__(self):
self.__private_attr = 42
def get_private_attr(self):
return self.__private_attr
def set_private_attr(self, value):
self.__private_attr = value
obj = MyClass()
print(obj.get_private_attr()) # Accessing the private attribute
You can also try this code with Online Python Compiler
Run Code
Output:
42
Reading Values from Private Methods
In Python, you can access private attributes through getter methods. These methods allow you to read the values of private attributes indirectly, ensuring that you maintain encapsulation and control over the attribute's accessibility while providing a clear interface for retrieving its value within your class.
Example
Python
class MyClass:
def __init__(self):
self.__my_private_var = 42
def get_private_var(self):
return self.__my_private_var
obj = MyClass()
value = obj.get_private_var()
print("Private Variable:", value)
You can also try this code with Online Python Compiler
Run Code
Output:
42
Importance of Getter and Setter in Python
The importance of Getter and Setter in Python are:-
- Getter and setter methods are used in Python to achieve encapsulation. They control the access to the private variables in Python.
- Getter and setter methods are also used to validate values assigned to the attributes. This prevents any invalid values from being initialised to the variables.
- Getter and Setter methods are also useful in data hiding. With the help of these OOPs methods, we can hide the implementation details of a class from external users.
- Getters and Setters are also useful in debugging large codes. By adding print statements with getter and setter methods, it becomes easier to track when the data is being accessed or modified.
Frequently Asked Questions
What is the setter method in Python?
Setters are methods in Object Oriented Programming languages that are used to modify and update the value of an attribute of an object. Certain constraints can also be applied along with setter methods. This ensures that the new values assigned to the attributes are valid.
What is the purpose of getter and Setter in Python?
Getter and setter methods are used in Python to achieve encapsulation. They control the access to the private and protected variables in Python. Also, they can be used in data hiding by hiding the implementation details of a class from external users.
Why should we use getters and setters in Python?
In object-oriented languages, getters and setters are commonly employed to achieve data encapsulation. This practice conceals an object class's attributes from external classes, preventing unintentional data manipulation by methods in other classes.
Does every class need getters and setters?
Getters and setters are optional and are typically utilized with public classes that have private fields. In cases where your stack/queue class requires methods like push(), pop(), drop(), etc., explicit getters and setters may not be necessary. For instance, push() can serve as a custom setter method.
Conclusion
Getter and Setter methods are used in Python for data encapsulation, thus allowing the programmers for increased control and maintainability of the source code. We have covered the implementation of getter and setter methods in Python using the normal function, property() function, and the @property decorator.
We hope this blog has helped you understand the concept of getter and Setter in Python. Keep learning! We recommend you read some of our other articles on Python:
- Data Structures in Python
- Fibonacci Series in Python
- Leap year program in python
Refer to our Guided Path to upskill yourself.
Also check out the Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc.