定义一个Shape类,记录任意形状的位置,在Shape类的基础上派生出一个Rectangle 类和一个Circle 类,在Rectangle 类的基础上派生出一个Square 类,必须保证每个类都有计算面积和周长的功能
时间: 2024-05-16 17:17:03 浏览: 27
以下是定义Shape、Rectangle、Circle和Square类的代码,实现了计算面积和周长的功能:
```python
import math
class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
def area(self):
pass
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, x, y, width, height):
super().__init__(x, y)
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, x, y, radius):
super().__init__(x, y)
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
class Square(Rectangle):
def __init__(self, x, y, side):
super().__init__(x, y, side, side)
def area(self):
return self.width ** 2
def perimeter(self):
return 4 * self.width
```
可以按照以下方式使用这些类:
```python
rectangle = Rectangle(0, 0, 5, 10)
print(rectangle.area()) # 输出 50
print(rectangle.perimeter()) # 输出 30
circle = Circle(0, 0, 3)
print(circle.area()) # 输出 28.274333882308138
print(circle.perimeter()) # 输出 18.84955592153876
square = Square(0, 0, 5)
print(square.area()) # 输出 25
print(square.perimeter()) # 输出 20
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)