Circle2D Class in Python: Implementation and Usage
Circle2D Class in Python: Implementation and Usage
This guide explores the implementation and usage of a Circle2D class in Python. The Circle2D class represents a circle in a two-dimensional space, providing methods for calculating its area, perimeter, and determining if a point or another circle is contained within it or overlaps.
UML Diagram
The UML diagram for the Circle2D class is as follows:
---------------------------------------
| Circle2D |
---------------------------------------
| - x: double |
| - y: double |
| - radius: double |
---------------------------------------
| + Circle2D() |
| + Circle2D(x: double, y: double, |
| radius: double) |
| + getX(): double |
| + getY(): double |
| + getRadius(): double |
| + getArea(): double |
| + getPerimeter(): double |
| + contains(x: double, y: double): |
| boolean |
| + contains(circle: Circle2D): |
| boolean |
| + overlaps(circle: Circle2D): |
| boolean |
---------------------------------------
Python Implementation
Here's the Python implementation of the Circle2D class:
import math
class Circle2D:
def __init__(self, x=0, y=0, radius=1):
self.x = x
self.y = y
self.radius = radius
def getX(self):
return self.x
def getY(self):
return self.y
def getRadius(self):
return self.radius
def getArea(self):
return math.pi * self.radius ** 2
def getPerimeter(self):
return 2 * math.pi * self.radius
def contains(self, x, y):
distance = math.sqrt((x - self.x)**2 + (y - self.y)**2)
return distance <= self.radius
def contains(self, circle):
distance = math.sqrt((circle.x - self.x)**2 + (circle.y - self.y)**2)
return (distance + circle.radius) <= self.radius
def overlaps(self, circle):
distance = math.sqrt((circle.x - self.x)**2 + (circle.y - self.y)**2)
return distance < (circle.radius + self.radius)
Test Program
The following test program demonstrates the usage of the Circle2D class:
c1 = Circle2D(2, 2, 5.5)
print('Area:', c1.getArea())
print('Perimeter:', c1.getPerimeter())
print('Contains (3, 3):', c1.contains(3, 3))
print('Contains Circle2D(4, 5, 10.5):', c1.contains(Circle2D(4, 5, 10.5)))
print('Overlaps Circle2D(3, 5, 2.3):', c1.overlaps(Circle2D(3, 5, 2.3)))
This program creates a Circle2D object with center coordinates (2, 2) and radius 5.5. It then calculates and displays the circle's area, perimeter, and the results of the containment and overlap checks.
By using the Circle2D class, you can conveniently represent and manipulate circles within your Python programs, enabling various geometric calculations and operations.
原文地址: https://www.cveoy.top/t/topic/wXc 著作权归作者所有。请勿转载和采集!