定义图形类的子类:圆形类和矩形类,分别计算周长和面积
时间: 2024-11-11 21:14:49 浏览: 7
在面向对象编程中,你可以定义一个名为`Shape`的抽象基类,作为图形的通用模板,包含一些共性的属性和方法,比如`area`(面积)和`perimeter`(周长)的计算。然后,为具体的形状如圆形和矩形创建子类:
```python
class Shape:
def __init__(self, radius=None, width=None, height=None):
self.radius = radius
self.width = width
self.height = height
# 共享方法,子类需要覆盖
def calculate_area(self):
pass
def calculate_perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
super().__init__(radius=radius)
self.radius = radius
def calculate_area(self):
return 3.14 * (self.radius ** 2)
def calculate_perimeter(self):
return 2 * 3.14 * self.radius
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__(width=width, height=height)
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
def calculate_perimeter(self):
return 2 * (self.width + self.height)
# 示例:
circle = Circle(5)
print("Circle Area:", circle.calculate_area())
print("Circle Perimeter:", circle.calculate_perimeter())
rectangle = Rectangle(10, 7)
print("Rectangle Area:", rectangle.calculate_area())
print("Rectangle Perimeter:", rectangle.calculate_perimeter())
```
阅读全文