Python Programming - Encapsulation - Discussion

Discussion Forum : Encapsulation - General Questions (Q.No. 67)
67.
In Python, what is the primary benefit of using a property with a setter method?
class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height

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

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

    @width.setter
    def width(self, value):
        if value > 0:
            self._width = value
        else:
            raise ValueError("Width must be greater than 0.")
It allows read-only access to the width property
It provides write access to the width property with validation
It creates a new instance of the class
It exposes all internal details of the class
Answer: Option
Explanation:
The @width.setter decorator allows write access to the 'width' property with the provided validation in the setter method.
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.