We have seen in our previous code examples that we can access the instance attributes without any restrictions. We also implemented instance methods and we have no restriction on the use of these. We emulate to define them as private or protected, which works to hide the data and actions from the outside world.
But in real-world problems, we need to provide access to the variables in a way that is controllable and easy to maintain. This is achieved in many object-oriented languages through access modifiers such as getters and setters, which are defined next:
• Getters: These are methods used to access the private attributes from a class or its instance
• Setters: These are methods used to set the private attributes of a class or its instance.
Getters and setters methods can also be used to implement additional logic of accessing or setting the attributes, and it is convenient to maintain such an additional logic in one place. There are two ways to implement the getters and setters methods: a traditional way and a decorative way.
Using traditional getters and setters
Traditionally, we write the instance methods with a get and set prefix, followed by the underscore and the variable name. We can transform our Car class to use the getter and setter methods for instance attributes, as follows:
#carexample6.py
class Car:
__mileage_units = "Mi"
def __init__(self, col, mil):
self.__color = col
self.__mileage = mil
def __str__(self):
return f"car with color {self.get_color()} and \
mileage {self.get_mileage()}"
def get_color(self):
return self.__color
def get_mileage(self):
return self.__mileage
def set_mileage (self, new_mil):
self.__mileage = new_mil
if __name__ == "__main__":
car = Car ("blue", 1000)
print (car)
print (car.get_color())
print(car.get_mileage())
car.set_mileage(2000)
print (car.get_color())
print(car.get_mileage())
In this updated Car class, we added the following:
• color and mileage instance attributes were added as private variables.
• Getter methods for color and mileage instance attributes.
• A setter method only for the mileage attribute because color usually doesn't change once it is set at the time of object creation.
• In the main program, we get data for the newly created instance of the class using getter methods. Next, we updated the mileage using a setter method, and then we got data again for the color and mileage attributes.
The console output of each statement in this example is trivial and as per expectations. As mentioned, we did not define a setter for each attribute, but only for those attributes where it makes sense and the design demands. Using getters and setters is a best practice in OOP, but they are not very popular in Python. The culture of Python developers (also known as the Pythonic way) is still to access attributes directly.
0 comments:
Post a Comment