Getters and Setters are methods within the class to access (get) or modify (set) any attribute in the object.
<aside> 💡
Getter: returns value of property. Setter: changes value of property
</aside>
Getters and Setters implementation:
# Getter and Setter
class Student:
def __init__(self, sid, name, major):
# Public attributes
self.sid = sid
self.name = name
self.major = major
# Getter Methods
def getSID(self):
return self.sid
def getName(self):
return self.name
def getMajor(self):
return self.major
# Setter Methods, always take at least one argument
def setSID(self, sid):
self.sid = sid
def setName(self, name):
self.name = name
def setMajor(self, major):
self.major = major
def main():
s = Student(100001, "James Arthur", "IT")
print("==============================")
print("Student Information")
# Getter methods to get the attributes
print("Student ID:", s.getSID())
print("Student Name:", s.getName())
print("Major:", s.getMajor())
print("==============================")
main()
Output:
==============================
Student Information
Student ID: 100001
Student Name: James Arthur
Major: IT
==============================
Setter method:
def main():
s = Student(100001, "James Arthur", "IT")
# Setter methods to modify the attributes
s.setMajor("MARKETING")
print("==============================")
print("Student Information")
# Since these are public attributes, we can just get them
# Using the attribute call
print("Student ID:", s.sid)
print("Student Name:", s.name)
print("Major:", s.major)
print("==============================")
main()
Output:
==============================
Student Information
Student ID: 100001
Student Name: James Arthur
Major: MARKETING
==============================
Getters and Setters for Private Attributes (Read-Only Attributes): We cannot retrieve these private attributes outside of the class defining them. Instead, we use getter and setter methods to return and modify the related private attribute:
# Getter and Setter
class Student:
def __init__(self, sid, name, major):
# Private attributes
self.__sid = sid
self.__name = name
self.__major = major
# Getter Methods
def getSID(self):
return self.__sid
def getName(self):
return self.__name
def getMajor(self):
return self.__major
# Setter Methods, always take at least one argument
def setSID(self, sid):
self.__sid = sid
def setName(self, name):
self.__name = name
def setMajor(self, major):
self.__major = major
def main():
s = Student(100001, "James Arthur", "IT")
print("==============================")
print("Student Information")
# Getter methods to get the attributes
print("Student ID:", s.getSID())
print("Student Name:", s.getName())
print("Major:", s.getMajor())
print("==============================")
s.setMajor("MARKETING")
print("Major Updated:", s.getMajor())
main()
Output:
==============================
Student Information
Student ID: 100001
Student Name: James Arthur
Major: IT
==============================
Major Updated: MARKETING