-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Square: def __init__(self, length, wide): self.length = length self.wide = wide def girth(self): return (self.length + self.wide) * 2 def area(self): return self.length * self.wide S1 = Square(3, 2) print(S1.girth())
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point: def __init__(self,x1,y1): self.x = x1 self.y = y1 def distance(self,other): return ((self.x -other.x)**2 + (self.y-other.y)**2)**0.5 p1 = Point(1, 2) p2 = Point(4, 5) print(p1.distance(p2))
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
from math import pi class Circle: def __init__(self,b1,x1=0,y1=0): self.radius = b1 self.centre1 = x1 self.centre2 = y1 def circle_girth(self): return pi*2*self.radius def circle_area(self): return 2*pi*self.radius**2 def waiqie(self, other): if self.radius + other.radius == ((self.centre1-other.centre1)**2+(self.centre2-other.centre2)**2)**0.5: return '是外切' else: return '不是外切' c1 = Circle(1,3,2) c2 = Circle(2,4,3) print(c1.waiqie(c2))
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Piont: def __init__(self,x1,y2): self.x = x1 self.y = y2 def distance(self,other): return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5 p1 = Point(1, 2) p2 = Point(3, 4) print(p1.distance(p2))
-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog: def __init__(self, n, s, p): self.name = n self.sex = s self.pinz = p def print_imf(self): return '汪汪' d1 = Dog('小花', '母', '田园') animal = d1.name class Human: def __init__(self, n, age1, animal): self.name = n self.age = age1 self.animal = animal def liu_gou(self): return return f'{self.name}遛{self.animal}' h1 = Human('罗', 18, animal=animal) print(h1.liu_gou()) #罗遛小花
day17-面向对象作业
最新推荐文章于 2023-12-21 21:11:12 发布