Python Property

http‮‬s://www.theitroad.com

In Python, properties are a way to define getters, setters, and deleters for class attributes. They allow you to encapsulate the access to an attribute and add additional logic to it.

Here's an example of how to define a property in Python:

class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, value):
        if value <= 0:
            raise ValueError("Width must be positive")
        self._width = value

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, value):
        if value <= 0:
            raise ValueError("Height must be positive")
        self._height = value

    @property
    def area(self):
        return self._width * self._height

In this example, we define a class Rectangle with two private attributes _width and _height. We then define three properties: width, height, and area.

The width property defines a getter and a setter method using the @property and @width.setter decorators, respectively. The getter returns the value of the _width attribute, and the setter validates the input before setting the attribute. If the value is not positive, it raises a ValueError exception.

The height property is defined in the same way as the width property, but it uses the _height attribute instead.

The area property is defined only with a getter method using the @property decorator. It calculates and returns the area of the rectangle.

We can now use these properties to access and modify the attributes of a Rectangle object:

rect = Rectangle(3, 4)
print(rect.width)  # 3
print(rect.height)  # 4
print(rect.area)  # 12

rect.width = 5
rect.height = 6
print(rect.area)  # 30

rect.width = -1  # ValueError: Width must be positive

In this example, we create a Rectangle object with a width of 3 and a height of 4. We then use the width, height, and area properties to access and calculate the attributes of the rectangle. We also modify the width and height of the rectangle using the width and height properties. When we try to set the width to a negative value, it raises a ValueError exception as defined in the width property setter.