设计一个绘图的基类图形类 Graphic,在 Graphic 类中添加计算图形面积函数 CalArea(),图形绕点旋转函数 Rotate(float x, float y),判断点是否在图形 内部函数 IsInsideGraphic(float x, float y) 。 从 Graphic 派生矩形 Rectangle,圆 Circle,三角形 Triangle 等类,将上述三个函数在子类中重新 设计其功能,设计主函数测试三个类
时间: 2024-03-10 22:47:12 浏览: 18
好的,我理解了你的问题。这里是一个可能的解决方案:
```python
class Graphic:
def __init__(self, x, y):
self.x = x
self.y = y
def CalArea(self):
pass
def Rotate(self, x, y):
pass
def IsInsideGraphic(self, x, y):
pass
class Rectangle(Graphic):
def __init__(self, x, y, width, height):
super().__init__(x, y)
self.width = width
self.height = height
def CalArea(self):
return self.width * self.height
def Rotate(self, x, y):
# 绕点旋转
pass
def IsInsideGraphic(self, x, y):
if (x >= self.x and x <= self.x + self.width and y >= self.y and y <= self.y + self.height):
return True
else:
return False
class Circle(Graphic):
def __init__(self, x, y, radius):
super().__init__(x, y)
self.radius = radius
def CalArea(self):
return 3.14 * self.radius * self.radius
def Rotate(self, x, y):
# 绕点旋转
pass
def IsInsideGraphic(self, x, y):
if ((x - self.x) * (x - self.x) + (y - self.y) * (y - self.y) <= self.radius * self.radius):
return True
else:
return False
class Triangle(Graphic):
def __init__(self, x1, y1, x2, y2, x3, y3):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.x3 = x3
self.y3 = y3
def CalArea(self):
return abs((self.x1 * (self.y2 - self.y3) + self.x2 * (self.y3 - self.y1) + self.x3 * (self.y1 - self.y2)) / 2)
def Rotate(self, x, y):
# 绕点旋转
pass
def IsInsideGraphic(self, x, y):
b1 = (x - self.x1) * (self.y2 - self.y1) - (y - self.y1) * (self.x2 - self.x1) < 0
b2 = (x - self.x2) * (self.y3 - self.y2) - (y - self.y2) * (self.x3 - self.x2) < 0
b3 = (x - self.x3) * (self.y1 - self.y3) - (y - self.y3) * (self.x1 - self.x3) < 0
if ((b1 == b2) and (b2 == b3)):
return True
else:
return False
# 测试
rect = Rectangle(0, 0, 5, 4)
print(rect.CalArea())
print(rect.IsInsideGraphic(3, 2))
circ = Circle(0, 0, 5)
print(circ.CalArea())
print(circ.IsInsideGraphic(3, 2))
tri = Triangle(0, 0, 3, 0, 0, 4)
print(tri.CalArea())
print(tri.IsInsideGraphic(2, 2))
```
在这个解决方案中,我们定义了一个基类 `Graphic`,它包括三个函数:`CalArea()`、`Rotate()` 和 `IsInsideGraphic()`,它们分别用于计算图形的面积、绕点旋转和判断点是否在图形内部。然后我们从 `Graphic` 派生了三个子类 `Rectangle`、`Circle` 和 `Triangle`,并分别在子类中重新设计了这三个函数的功能。
在每个子类中,我们分别实现了这三个函数的具体操作。例如,在 `Rectangle` 类中,我们计算矩形面积的公式是 `width * height`,而判断点是否在矩形内部的方法是检查点的坐标是否在矩形的左上角和右下角之间。
最后,我们编写了一些测试代码,以确保我们的实现是正确的。