Getters and Setters in Python
Getters and Setters in Python:
Getters and setters in python are not the same as those in other object-oriented programming languages. Basically, the main purpose of using getters and setters in object-oriented programs is to ensure data encapsulation.
When to Use :
- We use getters and setters to add validation logic for getting and setting a value.
- To avoid direct access to a class field, private variables cannot be accessed directly or modified by any external user.
User-Defined getter and setter:
#python Program
#Rishikesh
#Getters and setter
class A(object):
def __init__(self):
self.name = None
self.userid=0
#getter
def get_name(self):
return (self.name)
#setter
def set_name(self,x):
self.name=x
ob = A()
ob.set_name(‘PrepSter’)
print(ob.get_name())
Output:
Prepster
Property Function for getter and setter:
- Property() is a built-in function that creates and returns a property object in Python.
- It has three methods:-
- getter()
- setter()
- delete()
Syntax:
property(fget, fset, fdel, doc)
Parameters:
fget() – used to get the value of attribute
fset() – used to set the value of attribute
fdel() – used to delete the attribute value
doc() – string that contains the documentation (docstring) for the attribute
Return: Returns a property attribute from the given getter, setter and deleter.
#python Program
#Rishikesh
#Getters and setter
class A(object):
def __init__(self):
self._name = None
self.userid=0
#getter
def get_name(self):
print(‘IN getter’)
return (self._name)
#setter
def set_name(self,x):
print(‘In setter’)
self._name=x
def del_name(self):
print(‘Delete’)
del self._name
name=property(get_name,set_name,del_name)
ob = A()
ob.name=‘Prepster’
print(ob.name)
Output:
In setter
IN getter
Prepster
Login/Signup to comment