设计三个类Circle(圆)、Rectangle(矩形)和Triangle(三角形),继承并扩展Shape类。
时间: 2024-12-13 12:21:32 浏览: 1
在面向对象编程中,我们可以设计一个名为`Shape`的基础类作为所有图形的抽象模板,然后创建`Circle`、`Rectangle`和`Triangle`这三个具体的形状类,它们都从`Shape`类继承。这里是一个简单的Python示例:
```python
class Shape:
def __init__(self, color):
self.color = color
# 继承的通用方法,如绘制形状
def draw(self):
pass
class Circle(Shape):
def __init__(self, radius, color):
super().__init__(color)
self.radius = radius
# 重写draw方法,添加圆特定的行为
def draw(self):
print(f"Drawing a circle with radius {self.radius} and color {self.color}.")
class Rectangle(Shape):
def __init__(self, width, height, color):
super().__init__(color)
self.width = width
self.height = height
# 重写draw方法,添加矩形特定的行为
def draw(self):
print(f"Drawing a rectangle with width {self.width}, height {self.height}, and color {self.color}.")
class Triangle(Shape):
def __init__(self, base, height, color):
super().__init__(color)
self.base = base
self.height = height
# 重写draw方法,添加三角形特定的行为
def draw(self):
print(f"Drawing a triangle with base {self.base}, height {self.height}, and color {self.color}.")
# 使用例子
circle = Circle(5, "blue")
circle.draw() # 输出: Drawing a circle with radius 5 and color blue.
rectangle = Rectangle(10, 8, "green")
rectangle.draw() # 输出: Drawing a rectangle with width 10, height 8, and color green.
triangle = Triangle(6, 4, "red")
triangle.draw()
阅读全文