定义一个抽象形状(Shape)父类,其有一个未实现方法:计算面积 (get_area)
从父类继承了三个子类:圆形、矩形、三角形,三个子类重写计算面积方法(get_area)。
定义 total_area (shape) 函数计算圆形、矩形、三角形面积。
# 定义抽象父类Shape(包含未实现的get_area方法)
class Shape:
def get_area(self):
# 抽象方法,子类必须重写,否则调用时抛出异常
pass
# 子类1:圆形(需传入半径)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius # 存储半径
def get_area(self):
# 圆形面积公式:π×r²
import math
return math.pi * (self.radius ** 2)
# 子类2:矩形(需传入长和宽)
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length # 存储长
self.width = width # 存储宽
def get_area(self):
# 矩形面积公式:长×宽
return self.length * self.width
# 子类3:三角形(需传入底和高)
class Triangle(Shape):
def __init__(self, base, height):
self.base = base # 存储底
self.height = height # 存储高
def get_area(self):
# 三角形面积公式:(底×高)/2
return (self.base * self.height) / 2
# 计算多个图形的总面积
def total_area(shapes):
total = 0
for shape in shapes:
# 利用多态,自动调用对应子类的get_area方法
total += shape.get_area()
return total
circle = Circle(radius=5)
print(f"圆形面积;{circle.get_area():.2f}")
rectangle = Rectangle(length=4, width=6) # 创建长4、宽6的矩形对象
print(f"矩形面积:{rectangle.get_area():.2f}") # 输出:矩形面积:24.00
triangle = Triangle(base=5,height=8)
print(f"三角形面积:{triangle.get_area():.2f}")