-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
```python class Rectangle: def __init__(self,length,width): self.length = length self.widtn = width def Circumference(self): return 2*(self.length+self.widtn) def area(self): return self.length*self.widtn c1 = Rectangle(5,3) print(c1.Circumference()) print(c1.area()) ```
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
```python class Point: def __init__(self,x,y): self.x = x self.y = y def distance(self,point): return ((self.x-point.x)**2+(self.y-point.y)**2)**0.5 d1 = Point(1,4) d2 = Point(0,0) print(d1.distance(d2)) ```
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
```python class Circle: pi = 3.14 def __init__(self, r, point: tuple): self.r = r self.point = point def length(self): return Circle.pi * 2 * self.r def area(self): return Circle.pi * self.r ** 2 def externally_tangent(self,circles): result = ((self.point[0]-circles.point[0])**2 +(self.point[1]-circles.point[1])**2)**0.5 if result == self.r + circles.r: print('外切') else: print('不是外切') c1 = Circle(1,(0,0)) print(c1.length()) print(c1.area()) c2 = Circle(2,(3,1)) c1.externally_tangent(c2) ```
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
```python class Lines: def __init__(self,start:tuple,end:tuple): self.start = start self.end = end def get_length(self): return ((self.start[0]-self.end[0])**2+(self.start[1]-self.end[1])**2)**0.5 line1 = Lines((0,0),(1,0)) print(line1.get_length()) ```
day15-面向对象作业2
最新推荐文章于 2024-11-13 17:26:18 发布