day17-面向对象作业

it2025-03-21  12

定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积

class Orthogon: def __init__(self, long=0, wide=0): self.long = long self.wide = wide def perimeter(self): print('周长:', (self.long + self.wide) * 2) def area(self): print('面积:', self.long * self.wide) o1 = Orthogon(3, 4) o1.perimeter() # 周长: 14 o1.area() # 面积: 12

定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离

class Coordinates: def __init__(self, x=0, y=0): self.x = x self.y = y def print_coordinates(self): print("x : ", self.x, ", y: ", self.y) def distance(self, other): print('我和你的距离只有:', ((other.x-self.x)**2 + (other.y-self.y)**2)**0.5) p1 = Coordinates(23, 32) p2 = Coordinates(26, 36) p1.print_coordinates() # x : 0 , y: 0 p2.print_coordinates() # x : 23 , y: 32 p1.distance(p2) # 我和你的距离只有: 5.0

定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切

import math class Circle: def __init__(self, x, y, r): self.x = x self.y = y self.r = r def perimeter(self): print('周长:', 2*self.r*math.pi) def area(self): print('面积:', self.r**2*math.pi) def judge_circumscribed(self, other): if ((other.x-self.x)**2 + (other.y-self.y)**2)**0.5 == self.r + other.r: print('外切') else: print('不外切') c1 = Circle(4, 5, 3) c1.perimeter() # 周长: 18.84955592153876 c1.area() # 面积: 28.274333882308138 c2 = Circle(7, 9, 2) c1.judge_circumscribed(c2) # 外切

定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度

class Segment: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def obtain_length(self): print('线段长度:', ((self.x2-self.x1)**2+(self.y2-self.y1)**2)**0.5) s1 = Segment(1, 3, 7, 11) s1.obtain_length() # 线段长度: 10.0

定义一个狗类和一个人类:

狗拥有属性:姓名、性别和品种 拥有方法:叫唤

人类拥有属性:姓名、年龄、狗 拥有方法:遛狗

class Dog: def __init__(self, name, age, color): self.name = name self.age = age self.color = color def bark(self): print(f'{self.name}在嘤嘤嘤!') 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: print(f'{self.name}带着{self.dog.name}要饭!') else: print(f'没有狗和{self.name}去要饭!') d1 = Dog('来福', 2, '黄色') d1.bark() # 来福在嘤嘤嘤! p1 = Person('常威', 20, d1) p1.walk_dog() # 常威带着来福要饭! p2 = Person('常威', 20) p2.walk_dog() # 没有狗和常威去要饭!
最新回复(0)