-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle: """ 矩形类 """ def __init__(self,l=0, w=0): self.l = l self.w = w def perimeter(self): return (self.l + self.w) * 2 def area(self): return self.l * self.w l1 = Rectangle(5,10) print('矩形周长是:', l1.perimeter()) print('矩形面积是:', l1.area())
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Dot: ''' 点类 ''' def __init__(self,x=0,y=0): self.x = x self.y = y def distance(self,x1=0,y1=0): return ((self.x - x1)**2 + (self.y-y1)**2) ** 0.5 p1 = Dot() p1.x = 3 p1.y = 5 print('两点之间距离是:',p1.distance(1,1))
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle:
'''
圆类
'''
pi = 3.1415926
def __init__(self,r=0,x=0,y=0):
self.r = r
self.x = x
self.y = y
def perimeter(self):
return 2 * self.pi * self.r
def area(self):
return Circle.pi * self.r ** 2
def distance(self,new_circle):
l = ((c1.x - c2.x) ** 2 + (c1.y-c2.y) ** 2) ** 0.5
d = c1.r + c2.r
if l == d:
return True
else:
return False
c1 = Circle()
c1.r = 5
c1.x = 0
c1.y = 0
c2 = Circle()
c2.r = 10
c2.x = 5
c2.y = 9
print('圆1周长是',c1.perimeter())
print('圆1面积是',c1.area())
print(c1.distance(c2))
5.定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Segment:
"""
线段
"""
def __init__(self,x=0,y=0,x1=0,y1=0):
self.x = x
self.y = y
self.x1 = x1
self.y1 = y1
def distance(self):
return ((self.x - self.x1)**2 + (self.y-self.y1)**2) ** 0.5
d = Segment()
d.x = 0
d.y = 0
d.x1 = 5
d.y1 = 5
print('两点之间距离是:',d.distance())