欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python计算平面形体有周长和面积

程序员文章站 2024-03-12 20:10:20
...

4、对平面形体有周长和面积,周长、面积应怎样计算(用什么方法)?要求实现运行时的多态性。请编程,并测试。

Shape

正方形(Square) 长方形(Rectangle) 圆形(Circle) 圆环(Annulus)

#
import math


class Shape:

    def __init__(self, w, length=0) -> None:
        super().__init__()
        self.w = w
        self.length = length

    def area(self):
        pass

    def perimeter(self):
        pass


class Square(Shape):

    def __init__(self, w, length=0) -> None:
        super().__init__(w, length)

    def area(self):
        s = self.w ** 2
        return s

    def perimeter(self):
        c = 4 * self.w
        return c


# s1 = Square(4)
# print(s1.perimeter())
# print(s1.area())
class Rectangle(Shape):

    def __init__(self, w, length) -> None:
        super().__init__(w, length)

    def area(self):
        s = self.w * self.length
        return s

    def perimeter(self):
        c = (self.w + self.length) * 2
        return c


# r1 = Rectangle(4, 5)
# print(r1.perimeter())
# print(r1.area())
class Circle(Shape):

    def __init__(self, w, length=0) -> None:
        super().__init__(w, length)

    def area(self):
        s = math.pi * self.w * self.w
        return s

    def perimeter(self):
        c = math.pi * self.w * 2
        return c


# c1 = Circle(4)
# print(c1.perimeter())
# print(c1.area())
class Annulus(Shape):

    def __init__(self, w, length) -> None:
        super().__init__(w, length)

    def area(self):
        s = abs(math.pi * self.w * self.w - math.pi * self.length * self.length)
        return s

    def perimeter(self):
        c = math.pi * self.w * 2 + math.pi * self.length * 2
        return c


# a1 = Annulus(4, 5)
# print(a1.perimeter())
# print(a1.area())