Home »
Python »
Python programs
Python | Example to implement Getters and Setters in a class
Here, we are going to learn how to implement Getters and Setters in a class to access and set the data to the members of the class in Python?
Submitted by Pankaj Singh, on November 16, 2018
In this program, we are implementing Getters and Setters. Getters are used to access data members so they are also called accessors and Setters are used to change the data memebers values 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 :101
Enter Name :Pankaj
Enter Gender:Male
Enter City :Delhi
Enter Salary:70000
Displaying Employee Data:
Id : 101
Name : Pankaj
Gender : Male
City : Delhi
Salary : 70000
Python class & object programs »