Python:定义一个形状基类,并在其下定义子类,计算面积和周长

2021/5/30 1:21:03

本文主要是介绍Python:定义一个形状基类,并在其下定义子类,计算面积和周长,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

编写代码,定义一个形状基类,有 2 个属性:面积和周长,以及两个无返回值的方法:area()和 perimeter(),分别计算形状的面积和周长,从基类派生出三个子类:三角形、矩形、圆,重载基类的两个方法。

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:定义一个形状基类,并在其下定义子类,计算面积和周长的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程