Python设计两个类: 一个点类,属性包括x,y坐标。 一个Rectangle类(矩形) ,属性有左上角和右下角的坐标,可以计算矩形的面积;可以判断点是否
时间: 2024-10-23 20:14:25 浏览: 24
在Python中,你可以设计如下的两个类:
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# 点的相关方法,比如获取坐标、打印等
def get_coordinates(self):
return (self.x, self.y)
def __str__(self):
return f"Point ({self.x}, {self.y})"
class Rectangle:
def __init__(self, left_top_point, right_bottom_point):
self.left_top = left_top_point
self.right_bottom = right_bottom_point
self.width = right_bottom_point.x - left_top_point.x
self.height = right_bottom_point.y - left_top_point.y
# 计算矩形面积
def area(self):
return self.width * self.height
# 判断点是否在矩形内
def contains_point(self, point):
if point.get_coordinates()[0] >= self.left_top.x and \
point.get_coordinates()[0] <= self.right_bottom.x and \
point.get_coordinates()[1] >= self.left_top.y and \
point.get_coordinates()[1] <= self.right_bottom.y:
return True
else:
return False
# 以字符串形式表示矩形
def __str__(self):
return f"Rectangle ({self.left_top}, {self.right_bottom}) with area {self.area()}"
# 示例
pt = Point(2, 3)
rect = Rectangle(Point(0, 0), Point(5, 7))
print(f"Point at ({pt.x}, {pt.y}): {pt}")
print(f"Rectangle ({rect.left_top}, {rect.right_bottom}): Area = {rect.area()}")
if rect.contains_point(pt):
print("Point is inside the rectangle.")
else:
print("Point is not inside the rectangle.")
```
阅读全文