将几何区域系统的实现( 9.4节)重写为恰当的模块
时间: 2024-03-03 22:53:53 浏览: 7
好的,这是重写后的代码:
```python
import math
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self, other):
return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)
class Rectangle:
def __init__(self, posn, w, h):
self.corner = posn
self.width = w
self.height = h
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def contains(self, point):
return (self.corner.x <= point.x < self.corner.x + self.width and
self.corner.y <= point.y < self.corner.y + self.height)
class Circle:
def __init__(self, center, radius):
self.center = center
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
def contains(self, point):
return self.center.distance(point) < self.radius
```
将其保存为一个名为 `geometry.py` 的文件中,就可以作为一个模块使用了。在其他文件中,我们可以通过以下方式导入和使用:
```python
from geometry import Point, Rectangle, Circle
p = Point(1, 2)
r = Rectangle(p, 10, 20)
c = Circle(p, 5)
print(r.area()) # 输出 200
print(c.perimeter()) # 输出 31.41592653589793
print(r.contains(Point(5, 5))) # 输出 True
```