计算周长和面积(Python)

导入数学模块
import math

# 定义计算类
class Count():
    def __init__(self, long, wide,high):    # 传入长宽高
        self.long = long
        self.wide = wide
        self.high = high

    def perimeter(self):  # 定义计算周长方法
        # 判断两边之和大于第三边
        if self.long + self.wide > self.high and self.long + self.high > self.wide and self.wide + self.high >self.long:
            return self.long + self.wide + self.high
        else:
            return ("无法构成三角形")

    def area(self):     # 定义计算面积方法
        # 根据海伦公式 周长/2
        p1 = (self.long + self.wide + self.high) /2
        # 周长值 * (周长-long) * ... 并赋值给新变量(面积)
        p2 = p1 * (p1 - self.long) * (p1 - self.wide) * (p1 - self.high)
        # 返回面积的开方
        return math.sqrt(p2)

# 实例化对象
c = Count(5, 6, 7)
# 调用方法
print(c.perimeter())
print(c.area())

你可能感兴趣的:(Python,python)