Getter and Setter in Python : Getters and setters in Python are different from those in other OOP languages.The primary use of getters and setters is to insure data encapsulation in object- acquainted programs.
Unlike other object-oriented languages, private variables in Python are not hidden fields. Some OOPs languages use getter and setter methods for data encapsulation. We want to hide the properties of the object class from other classes so that methods in other classes don't inadvertently change the data.
In OOP languages, getters and setters are used to retrieve and update data. Getters retrieve the object's current property values, while setters change the object's property values. In this article, we will discuss getters and setters in Python using examples.
What is Getter and setter in Python?
Getters are methods in object-oriented programming (OOPS) for accessing private properties of a class. The setattr() function in Python is equivalent to the getattr() function in Python. It changes the property value of an object.
A setter is a method for setting the value of a property. In object-oriented programming, setting the value of a private property in a class is very useful.
Generally speaking, getters and setters are mainly used to ensure data encapsulation in OOP.
Use normal functions to implement getter and setter behavior:
If we specify the normal get() and set() methods to get the getters setters property, there is no special implementation.
Example:
Let s take an illustration to understand how we may use the normal function to achieve the getters and setter function.
class Javatpoint:
def __init__(self, age = 0):
self._age = age
# using the getter method
def get_age(self):
return self._age
# using the setter method
def set_age(self, a):
self._age = a
John = Javatpoint()
#using the setter function
John.set_age(19)
# using the getter function
print(John.get_age())
print(John._age)
Penetrating Private trait
class year_graduated:
def __init__(self, year=0):
self._year = year
# Instantiating the class
grad_obj = year_graduated()
#Printing the object
print(grad_obj)
#Printing the object attribute
print(grad_obj.year)
Output
<__main__ .year_graduated="" 0x00f2dd50="" at="" object="">
0
0 Comments