python语法练习题——————题目 3:多态特性

张开发
2026/4/18 3:24:25 15 分钟阅读

分享文章

python语法练习题——————题目 3:多态特性
Author:zhuyahao Time:2026/4/17 Desc:### 题目 3多态特性 定义一个 Shape 类有一个抽象方法 area方法体为空。 再定义 Rectangle 类和 Circle 类继承自 Shape 类 分别实现 area 方法计算矩形面积长 × 宽和圆的面积pi r^2)。 创建 Rectangle 和 Circle 类的对象将它们放入一个列表中遍历列表并调用每个对象的 area 方法。 import math class Shape: 形状基类 def area(self): 计算面积的抽象方法 pass class Rectangle(Shape): 矩形类 def __init__(self, width, height): self.width width self.height height def area(self): 计算矩形面积长 × 宽 return self.width * self.height def __str__(self): return f矩形(宽{self.width}, 高{self.height}) class Circle(Shape): 圆形类 def __init__(self, radius): self.radius radius def area(self): 计算圆的面积π × r² return math.pi * self.radius ** 2 def __str__(self): return f圆形(半径{self.radius}) if __name__ __main__: # 创建不同形状的对象 rect1 Rectangle(5, 10) rect2 Rectangle(3, 7) circle1 Circle(4) circle2 Circle(2.5) # 将所有形状对象放入列表 shapes [rect1, circle1, rect2, circle2] print( * 50) print(遍历形状列表计算每个形状的面积) print( * 50) # 遍历列表调用每个对象的 area 方法多态的体现 for shape in shapes: print(f{shape} 的面积{shape.area():.2f}) print(\n * 50) print(验证继承关系) print( * 50) print(frect1 是 Shape 的实例{isinstance(rect1, Shape)}) print(fcircle1 是 Shape 的实例{isinstance(circle1, Shape)}) print(frect1 是 Rectangle 的实例{isinstance(rect1, Rectangle)}) print(fcircle1 是 Circle 的实例{isinstance(circle1, Circle)})

更多文章