Here, we will figure out how to actualize Getters and Setters in a class to access and set the information to the individuals from the class in Python?
In this program, we are actualizing Getters and Setters. Getters are utilized to get to information individuals so they are likewise called accessors and Setters are utilized to change the information members esteems so they are called Mutators.
Program:
class Employee:
def __init__(self): #Constructor
self.__id = 0
self.__name = ""
self.__gender = ""
self.__city = ""
self.__salary = 0
def getId(self): #Accessor/Getters
return self.__id
def setId(self,id): #Mutators/Setters
self.__id=id
def getName(self):
return self.__name
def setName(self,name):
self.__name=name
def getGender(self):
return self.__gender
def setGender(self,gender):
self.__gender=gender
def getCity(self):
return self.__city
def setCity(self,city):
self.__city=city
def getSalary(self):
return self.__salary
def setSalary(self,salary):
self.__salary=salary
def main():
print("Enter Employee Data:")
id = int(input("Enter Id\t:"))
name = input("Enter Name\t:")
gender = input("Enter Gender:")
city = input("Enter City\t:")
salary = int(input("Enter Salary:"))
e=Employee()
e.setId(id)
e.setName(name)
e.setGender(gender)
e.setCity(city)
e.setSalary(salary)
id2 = e.getId()
name2 = e.getName()
gender2 = e.getGender()
city2 = e.getCity()
salary2 = e.getSalary()
print("\nDisplaying Employee Data:")
print("Id\t\t:", id2)
print("Name\t:", name2)
print("Gender\t:", gender2)
print("City\t:", city2)
print("Salary\t:", salary2)
if __name__=="__main__":
main()
Output:
Enter Employee Data:
Enter Id :121
Enter Name :Kishan
Enter Gender:male
Enter City :Raipur
Enter Salary:75000
Displaying Employee Data:
Id : 121
Name : Kishan
Gender : Male
City : Raipur
Salary : 75000