class里的静态方法 @staticmethod
- 这个静态方法是属于该类的,而不属于该类创建的对象
from math import sqrt
class Triangle(object):
def __init__(self,a,b,c):
self._a = a
self._b = b
self._c = c
@staticmethod
def is_valid(a, b, c):
return a + b > c and b + c > a and a + c > b
def perimeter(self):
return self._a + self._b + self._c
def area(self):
half = self.perimeter() / 2
return sqrt(half * (half - self._a) *
(half - self._b) * (half - self._c))
def main():
a = int(input('请输入第一条边的长度:'))
b = int(input('请输入第二条边的长度:'))
c = int(input('请输入第三条边的长度:'))
if Triangle.is_valid(a, b, c):
t = Triangle(a, b, c)
print('三角形的边长为:' + str(t.perimeter()))
print('三角形的面积为:' + str(t.area()))
else:
print('输入的三条边不能构成三角形')
if __name__ == '__main__':
main()
运行结果: