Sunday, March 20, 2022

Using property decorators

Using a decorator to define getters and setters is a modern approach that helps to achieve the Python way of programming.

If you are into using decorators, then we have a @property decorator in Python to make the code simpler and cleaner. The Car class with traditional getters and setters is updated with decorators, and here is a code snippet showing this:

carexample7.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.color} and mileage \

{self.mileage}"

@property

def color(self):

return self.__color

@property

def mileage(self):

return self.__mileage

@mileage.setter

def mileage (self, new_mil):

self.__mileage = new_mil

if __name__ == "__main__":

car = Car ("blue", 1000)

print (car)

print (car.color)

print(car.mileage)

car.mileage = 2000

print (car.color)

print(car.mileage)

In this updated class definition, we updated or added the following:

• Instance attributes as private variables

• Getter methods for color and mileage by using the name of the attribute as the method name and using @property

• Setter methods for mileage using the @mileage.setter decorator, giving the method the same name as the name of the attribute

In the main script, we access the color and the mileage attributes by using the instance name followed by a dot and the attribute name (the Pythonic way). This makes the code syntax concise and readable. The use of decorators also makes the name of the methods simpler.

So we have discussed all aspects of encapsulation in Python, using classes for the bundling of data and actions, hiding unnecessary information from the outside world of a class, and how to protect data in a class using getters, setters, and property features of Python. In the next post, we will discuss how inheritance is implemented in Python.

Share:

0 comments:

Post a Comment