设计一个Circle(圆)类,包括圆心位置`,半径,颜色等属性。编写构造方法和其他方法, 计算周长和面积。请编写程序验证类的功能。
时间: 2024-05-02 07:21:37 浏览: 78
构造一个圆形类,求面积和周长
```python
class Circle:
def __init__(self, x=0, y=0, radius=0, color='black'):
self.x = x
self.y = y
self.radius = radius
self.color = color
def get_area(self):
return 3.14 * self.radius ** 2
def get_perimeter(self):
return 2 * 3.14 * self.radius
def __str__(self):
return f"Circle with center at ({self.x}, {self.y}), radius {self.radius}, color {self.color}"
```
测试代码:
```python
c1 = Circle(0, 0, 5, 'red')
print(c1)
print('Area:', c1.get_area())
print('Perimeter:', c1.get_perimeter())
c2 = Circle(3, 4, 2)
print(c2)
print('Area:', c2.get_area())
print('Perimeter:', c2.get_perimeter())
```
输出结果:
```
Circle with center at (0, 0), radius 5, color red
Area: 78.5
Perimeter: 31.400000000000002
Circle with center at (3, 4), radius 2, color black
Area: 12.56
Perimeter: 12.56
```
阅读全文