-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class rectangle: def __init__(self, length, width): self.width = width self.length = length def area(self): return self.width * self.length def girth(self): return (self.width + self.length) * 2 a1 = rectangle(2,4) print(a1.area()) print(a1.girth())
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class twodimensionalpoint: def __init__(self, x, y): self.x = x self.y = y def distance(self,other): return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5 p1 = twodimensionalpoint(2,2) p2 = twodimensionalpoint(3,3) print(p1.distance(p2))
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class circle: pi =3.1415926 def __init__(self, x, y, r): self.x = x self.y = y self.r = r def area(self): return circle.pi * self.r ** 2 def girth(self): return 2 * circle.pi * self.r def isCircumscribed(self, other): if self.r + other.r == ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5: return '外切' else: return '不外切' a1 = circle(0,0,5) a2 = circle(8,0,3) print(a1.isCircumscribed(a2))
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class segment: pi =3.1415926 def __init__(self, x, y): self.x = x self.y = y def length(self): return ((self.y[1]-self.x[1]) ** 2 + (self.y[0]-self.x[0]) ** 2) ** 0.5 a1 = segment((0,0),(3,4)) print(a1.length())
day15-面向对象作业2
最新推荐文章于 2024-09-10 13:01:50 发布