import math class Graphic: def __init__(self,name): self.name = name def cal_square(self): pass class Triangle(Graphic): def __init__(self,name,height,border): super().__init__(name) self.height = height self.border = border def cal_square(self): square = 1/2 * self.height * self.border print(f"{self.name}的面积是{square:.2f}") class Circle(Graphic): def __init__(self,name,radius): super().__init__(name) self.radius = radius def cal_square(self): square = math.pi * pow(self.radius,2) print(f"{self.name}的面积是{square:.3f}") t1 = Triangle("三角形",6,8) t1.cal_square() c1 = Circle("圆",3) c1.cal_square()给每段代码加上注释
时间: 2024-04-27 18:25:02 浏览: 162
# 导入 math 模块
import math
# 定义图形类
class Graphic:
def __init__(self, name):
self.name = name
# 定义计算面积的方法,需要在子类中重写
def cal_square(self):
pass
# 定义三角形类,继承自图形类
class Triangle(Graphic):
def __init__(self, name, height, border):
super().__init__(name)
self.height = height
self.border = border
# 重写父类的计算面积方法
def cal_square(self):
square = 1/2 * self.height * self.border
print(f"{self.name}的面积是{square:.2f}")
# 定义圆形类,继承自图形类
class Circle(Graphic):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
# 重写父类的计算面积方法
def cal_square(self):
square = math.pi * pow(self.radius, 2)
print(f"{self.name}的面积是{square:.3f}")
# 创建三角形对象并调用计算面积方法
t1 = Triangle("三角形", 6, 8)
t1.cal_square()
# 创建圆形对象并调用计算面积方法
c1 = Circle("圆", 3)
c1.cal_square()
阅读全文