创建一个Shape基类和两个子类Rectangle和Circle,用Python完成
时间: 2025-01-28 11:16:37 浏览: 16
在Python中,你可以创建一个基础类Shape
,然后定义两个子类Rectangle
和Circle
来展示多态的概念。这里是一个简单的例子:
# 定义基础Shape类
class Shape:
def __init__(self, name):
self.name = name
# 简单的绘制方法
def draw(self):
print(f"{self.name}开始绘制...")
# 子类Rectangle,扩展基础形状
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__("矩形")
self.width = width
self.height = height
# 重写draw方法,添加矩形特有的操作
def draw(self):
print(f"{self.name}正在绘制,尺寸: {self.width}x{self.height}")
# 子类Circle,同样扩展基础形状
class Circle(Shape):
def __init__(self, radius):
super().__init__("圆形")
self.radius = radius
# 重写draw方法,添加圆的特性
def draw(self):
print(f"{self.name}正在绘制,半径: {self.radius}")
# 测试多态性
shapes = [Rectangle(5, 7), Circle(3)]
for shape in shapes:
shape.draw() # 尽管都是调用draw方法,但会根据实际对象类型显示相应信息
在这个例子中,虽然所有的draw()
调用看起来都是一样的,但是由于每个对象实际上属于Rectangle
或Circle
,所以它们的行为会有所不同。
相关推荐


















