请编写一个python程序,定义一个形状类,包含属性-形状名、面积、周长,除初始化方法外,定义方法-算面积,算周长。然后,定义三个子类,三角形、矩形、圆形,分别重写算面积、算周长的方法。最后,定义相应子类的对象来验证类是否成功定义。
时间: 2024-10-09 18:09:43 浏览: 42
当然,这是一个简单的Python程序示例,展示了如何创建一个基础形状类和它的几个子类:
```python
class Shape:
def __init__(self, name):
self.name = name
self.area = None
self.perimeter = None
# 定义通用的方法计算面积和周长
def calculate_area(self):
raise NotImplementedError("Subclasses must implement this method")
def calculate_perimeter(self):
raise NotImplementedError("Subclasses must implement this method")
class Triangle(Shape):
def __init__(self, base, height):
super().__init__("Triangle")
self.base = base
self.height = height
def calculate_area(self):
return 0.5 * self.base * self.height
def calculate_perimeter(self):
return self.base + self.height
class Rectangle(Shape):
def __init__(self, length, width):
super().__init__("Rectangle")
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
def calculate_perimeter(self):
return 2 * (self.length + self.width)
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
def calculate_area(self):
return 3.14159 * (self.radius ** 2)
def calculate_perimeter(self):
return 2 * 3.14159 * self.radius
# 测试和验证子类
triangle = Triangle(3, 4)
print(f"Triangle area: {triangle.calculate_area()}")
print(f"Triangle perimeter: {triangle.calculate_perimeter()}")
rectangle = Rectangle(5, 6)
print(f"Rectangle area: {rectangle.calculate_area()}")
print(f"Rectangle perimeter: {rectangle.calculate_perimeter()}")
circle = Circle(2)
print(f"Circular area: {circle.calculate_area()}")
print(f"Circular perimeter: {circle.calculate_perimeter()}")
阅读全文