-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rect: def __init__(self, long1=10, width1=20): self.long = long1 self.width = width1 def area(self): print(f'面积:{self.long * self.width}') def perimeter(self): print(f'周长:{(self.width +self.long)*2 }') r1 = Rect(20,30) r2 = Rect(10,30) r3 = Rect() r2.area() r1.perimeter() r3.area()
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Points: def __init__(self, x1=0, y1=0): self.x = x1 self.y = y1 def distance(self, point): long = ((self.x-point.x)**2 + (self.y-point.y)**2)**0.5 return long p1 = Points(60, 10) p2 = Points(10, 20) print(f'两点距离:{p1.distance(p2)}')
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle: def __init__(self, mid_point_x1=0, mid_point_y1=0, r_=1): self.mid_point_x = mid_point_x1 self.mid_point_y = mid_point_y1 self.r = r_ def area(self): print(f'面积:{3.14*self.r**2}') def perimeter(self): print(f'周长:{2*3.14*self.r}') def qie(self, point): mid_distence = ((self.x-point.x)**2 + (self.y-point.y)**2)**0.5 if mid_distence == self.r + point.r: return True else: return False
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line: def __init__(self, stx=0, sty=0, endx=0, endy=0): self.stx = stx self.sty = sty self.endx = endx self.endy = endy def long(self): l = ((self.stx - self.endx)**2 + (self.sty - self.endy )**2)**0.5 return l
-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dogs:
def __init__(self, name1, gender1, type1):
self.name = name1
self.gender = gender1
self.type = type1
def bark(self):
print('叫唤')
class Person:
def __init__(self, name, age,dog):
self.name = name
self.age = age
self.dog = dog