Curriculum
In Python, the property class is used to create “getter” and “setter” methods for class attributes. This allows us to define custom logic for accessing and modifying class attributes, rather than simply directly accessing or modifying them. The property class provides an alternative way to define getters and setters, as compared to using the @property and @<attribute_name>.setter decorators.
Here’s an example of how the property class can be used to create a getter and setter for a class attribute:
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
def get_width(self):
return self._width
def set_width(self, value):
if value < 0:
raise ValueError("Width must be positive")
self._width = value
def get_height(self):
return self._height
def set_height(self, value):
if value < 0:
raise ValueError("Height must be positive")
self._height = value
width = property(get_width, set_width)
height = property(get_height, set_height)
def area(self):
return self._width * self._height
r = Rectangle(10, 5)
print(r.area()) # 50
r.width = 15
r.height = 7
print(r.area()) # 105
r.width = -1 # ValueError: Width must be positive
In this example, we define a Rectangle class with width and height attributes, and an area() method that calculates the area of the rectangle. We define get_width, set_width, get_height, and set_height methods to provide custom logic for accessing and modifying the width and height attributes.
We then use the property class to create getter and setter methods for the width and height attributes. We pass the getter and setter methods to the property constructor, and assign the resulting object to the width and height attributes of the class.
When we create a Rectangle object r with a width of 10 and a height of 5, we can use the area() method to calculate the area of the rectangle, which is 50. We can also use the width and height attributes to get and set the values of the corresponding class attributes.
When we try to set the width attribute to a negative value, a ValueError is raised, because the set_width method validates the user input and ensures that the value is positive.
Using the property class allows us to define a simple and intuitive interface for working with class attributes, while still providing the flexibility to perform custom logic as needed. It can be useful in situations where more complex logic is needed for attribute access and modification, beyond what can be provided by the simple @property and @<attribute_name>.setter decorators.