# day-17 面向对象作业(2022.05.06)

13 篇文章 0 订阅
1. 定义一个狗类和一个人类：

class Dog:
def __init__(self, dname, dgender='公', dbreed='土狗'):
self.dname = dname
self.dgender = dgender
self.dbreed = dbreed

def bark(self):
return f'一只名叫{self.dname}的{self.dgender}{self.dbreed}在汪汪汪！'

dog1 = Dog('哮天犬','公','黑狗')  # 一只名叫哮天犬的公黑狗在汪汪汪！
print(dog1.bark())

class Person:
def __init__(self, name, age, dog=None ):
self.name = name
self.age = age
self.dog = dog

def walk_dog(self):
if self.dog:
return f'{self.age}岁的{self.name}在遛{self.dog}'
else:
return ('没有狗，自己遛')

p1 = Person('二郎神', 500, Dog('哮天犬').dname)
print(p1.walk_dog())    # 500岁的二郎神在遛哮天犬

1. 定义一个矩形类，拥有属性：长、宽 拥有方法：求周长、求面积
class Rect:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def perimeter(self):
return 2 * (self.x + self.y)

def area(self):
return self.x * self.y

r1 = Rect(1,2)
print(r1.perimeter(),r1.area())		# 6 2

1. 定义一个二维点类，拥有属性：x坐标、y坐标 拥有方法：求当前点到另外一个点的距离
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y

def distance(self,other):
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5

@staticmethod
def distance2(point1, point2):
return ((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2) ** 0.5

p1 = Point(9,8)
p2 = Point(1,2)
print(p1.distance(p2))  # 10.0
print(Point.distance2(p1,p2))   # 10.0

1. 定义一个圆类，拥有属性：半径、圆心 拥有方法：求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle:
pi = 3.1415926

def __init__(self,r,center=Point(0,0)):
self.r = r
self.center = center

def area(self):
return Circle.pi * self.r ** 2

def perimeter(self):
return 2 * Circle.pi * self.r

def isexcircle(self,other):
if self.center.distance(other.center) == self.r + other.r:
return f'圆心坐标为{other.center.x,other.center.y}半径为{other.r}的圆和圆心坐标为{self.center.x,self.center.y}半径为{self.r }的圆是外切圆'
return '两圆不是外切圆'

p1 = Circle(5,Point(9,8))
p2 = Circle(5,Point(1,2))
print(p1.isexcircle(p2))    # 圆心坐标为(1, 2)半径为5的圆和圆心坐标为(9, 8)半径为5的圆是外切圆

1. 定义一个线段类，拥有属性：起点和终点， 拥有方法：获取线段的长度
class Line:
def __init__(self,start=Point(0,0),end=Point(0,0)):
self.start = start
self.end = end

def lenth(self):
return self.start.distance(self.end)

l1 = Line(Point(1,2), Point(9,8))
print(l1.lenth())   # 10.0

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
12-03
06-27
04-17
11-08
04-18 422
09-26 797

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。