Home » 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.