-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrectangle.py
More file actions
77 lines (62 loc) · 2.09 KB
/
rectangle.py
File metadata and controls
77 lines (62 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from shape import Shape
from utils import validate_number
import math
class Rectangle(Shape):
"""
Represents a rectangle shape inheriting from Shape.
Attributes:
x (float): The x-coordinate of the top-left corner.
y (float): The y-coordinate of the top-left corner.
width (float): Rectangle width (must be positive).
height (float): Rectangle height (must be positive).
"""
def __init__(self, x: float = 0, y: float = 0, width: float = 1, height: float = 1):
super().__init__(x, y)
self.width = width
self.height = height
@property
def width(self) -> float:
return self._width
@width.setter
def width(self, value: float):
validate_number(value)
if value < 0:
raise ValueError("The width cannot be negative")
self._width = float(value)
@property
def height(self) -> float:
return self._height
@height.setter
def height(self, value: float):
validate_number(value)
if value < 0:
raise ValueError("The height cannot be negative")
self._height = float(value)
@property
def area(self) -> float:
"""Return the area of the rectangle"""
return self.width * self.height
@property
def perimeter(self) -> float:
"""Return the perimeter of the rectangle."""
return 2 * (self.width + self.height)
@property
def is_square(self) -> bool:
"""Check if the rectangle is a square."""
return math.isclose(self.width, self.height)
def __repr__(self) -> str:
return (
f"Rectangle(x={self.x}, y={self.y}, "
f"width={self.width}, height={self.height})"
)
def __str__(self) -> str:
return (
f"Rectangle (w={self.width}, h={self.height}) at ({self.x}, {self.y}). "
f"Area: {self.area:.2f}, Perimeter: {self.perimeter:.2f}"
)
if __name__ == "__main__":
r = Rectangle(width=4, height=6)
print(r)
print("Is square?", r.is_square)
r.translate(5, 2)
print("Moved to:", (r.x, r.y))