class Shape: def __init__(self,areas = 0,perimeters = 0): self.areas = areas self.perimeters = perimeters #给shape赋予面积和周长变量 def area(): pass #定义area函数,不进行 *** 作 def perimeter(): pass #定义周长函数,不进行 *** 作 class Triangle(Shape): def __init__(self, a_sIDe = 0, b_sIDe = 0, c_sIDe = 0,areas = 0, perimeters = 0): super().__init__(areas, perimeters) self.a_sIDe = a_sIDe self.b_sIDe = b_sIDe self.c_sIDe = c_sIDe #定义子类三角形,赋予都有属性三边长,同时给予默认值0防止报错 def area(self): s = (self.a_sIDe + self.b_sIDe + self.c_sIDe) / 2 self.areas = (s * (s-self.a_sIDe) * (s-self.b_sIDe) * (s-self.c_sIDe))**0.5 #求三角形的面积 def perimeter(self): self.perimeters = self.a_sIDe + self.b_sIDe + self.c_sIDe #求周长class Circle(Shape): def __init__(self, radius = 0, areas = 0, perimeters = 0): super().__init__(areas, perimeters) self.radius = radius #定义子类圆,同时赋予独有属性半径,给予其默认值 def area(self): self.areas = (3.14 * (self.radius**2)) / 2 def perimeter(self): self.perimeters = 2 * 3.14 * self.radius #分别求面积周长并付给对应值 class Rectangle(Shape): def __init__(self, length = 0, wIDeth = 0, areas = 0, perimeters = 0): super().__init__(areas, perimeters) self.length = length self.wIDeth = wIDeth #定义子类矩形,独有属性长和宽,默认值均为零 def area(self): self.areas = self.length * self.wIDeth def perimeter(self): self.perimeters = 2 * (self.length + self.wIDeth) #分别求面积和周长 def area(self): self.areas = (3.14 * (self.radius**2)) / 2 def perimeter(self): self.perimeters = 2 * 3.14 * self.radius #分别求面积周长并付给对应值 class Rectangle(Shape): def __init__(self, length = 0, wIDeth = 0, areas = 0, perimeters = 0): super().__init__(areas, perimeters) self.length = length self.wIDeth = wIDeth #定义子类矩形,独有属性长和宽,默认值均为零 def area(self): self.areas = self.length * self.wIDeth def perimeter(self): self.perimeters = 2 * (self.length + self.wIDeth) #分别求面积和周长#测试 a1 = Triangle(3,4,5)a1.area()a1.perimeter()print(a1.areas)print(a1.perimeters)#三角形(3,4,5)符合要求且正确a2 = Circle(5)a2.area()a2.perimeter()print(a2.areas)print(a2.perimeters)#矩形(3,4)符合要求且正确a3 = Rectangle(5)a3.area()a3.perimeter()print(a3.areas)print(a3.perimeters)#圆(5)符合要求且正确
总结 以上是内存溢出为你收集整理的Python:定义一个形状基类,并在其下定义子类,计算面积和周长全部内容,希望文章能够帮你解决Python:定义一个形状基类,并在其下定义子类,计算面积和周长所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)