-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog: def __init__(self, name, gender, variety): self.name = name self.gender = gender self.variety = variety def bark(self): print(f'{self.name}:汪汪汪') class Person: def __init__(self, name, age, dog): self.name = name self.age = age self.dog = None def walliuk_dog(self): if self.dog: print(f'{self.name}遛{self.dog.name}') else: print('没有狗,遛自己')
-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle: def __init__(self, lenth, width): self.lenth = lenth self.width = width def area(self): return self.lenth*self.width def girth(self): return 2*(self.lenth+self.width)
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Two_dimensional_point: 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
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle: pi = 3.1415926 def __init__(self, radius, center = Point): self.radius = radius self.center = center def area(self): return self.pi*self.radius**2 def girth(self): return 2*self.pi*self.radius def Circumscribe(self, other, radius): return self.center.distance(other.center) == self.radius + other.radius
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line: outset = (0, 0) end = (0, 0) def __init__(self,outset=Point(), end=Point()): self.outset = outset self.end = end def lenth(self): return self.start.distance(self.end)
day17-面向对象作业
最新推荐文章于 2024-03-06 19:44:34 发布