Property Decorators for Encapsulation
Property decorators in Python provide a clean and Pythonic way to manage attribute access, allowing you to control how attributes are accessed, modified, and deleted. This challenge will guide you through implementing property decorators to encapsulate attributes within a class, ensuring data integrity and providing a more controlled interface. It's a fundamental concept for object-oriented programming and building robust classes.
Problem Description
You are tasked with creating a Rectangle class that encapsulates its width and height attributes. Instead of directly accessing and modifying these attributes, you should use property decorators (@property, @width.setter, @height.setter) to provide controlled access. The property decorators should enforce the following rules:
- Validation: Both
widthandheightmust be positive numbers (greater than 0). If a non-positive value is provided, raise aValueErrorwith an appropriate message. - Getter: The
widthandheightproperties should return the current values of the attributes. - Setter: The
widthandheightsetters should validate the input and update the corresponding attributes only if the input is valid.
Examples
Example 1:
Input:
rectangle = Rectangle(width=5, height=10)
print(rectangle.width)
print(rectangle.height)
rectangle.width = 7
print(rectangle.width)
Output:
5
10
7
Explanation: The rectangle is initialized with width 5 and height 10. The width is then successfully updated to 7.
Example 2:
Input:
rectangle = Rectangle(width=5, height=10)
rectangle.width = -2
Output:
ValueError: Width must be a positive number.
Explanation: Attempting to set the width to a negative value raises a ValueError as expected.
Example 3:
Input:
rectangle = Rectangle(width=5, height=10)
rectangle.height = 0
Output:
ValueError: Height must be a positive number.
Explanation: Attempting to set the height to zero raises a ValueError.
Constraints
- The
Rectangleclass must havewidthandheightattributes. - The
widthandheightproperties must be implemented using@property,@width.setter, and@height.setterdecorators. - The validation logic must raise a
ValueErrorwith a descriptive message if the input is invalid. - The code should be well-structured and readable.
- The class should be able to handle both integer and float values for width and height.
Notes
- Consider using the
isinstance()function to check if the input values are numbers. - The setter methods should only update the attributes if the input is valid.
- Think about how to structure your code to keep it clean and maintainable. The use of property decorators is key to achieving encapsulation.
- Focus on the validation logic within the setter methods. This is the core of the challenge.