-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog: def __init__(self,d_name,d_gender,varieties,): self.d_name = d_name self.d_gender = d_gender self.d_varieties = varieties dog = Dog('有钱花','男孩','发金光') print(f'{dog.d_name}在叫唤') class Person: def __init__(self,name,age): self.name = name self.age = age self.dog = dog a = Person('周爽',22) print(f'{a.age}岁的{a.name}带着他{dog.d_varieties}的{dog.d_name}去浪')
-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangular: def __init__(self,long,wide): self.long = long self.wide = wide def area(self): return self.wide * self.long def perimeter(self): return (self.wide + self.long) * 2 b = Rectangular(2,2) print(b.area()) print(b.perimeter())
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point: def __init__(self,x,y): self.x = x self.y = y def distance(self,x1,y1): return ((self.x-x1)**2 + (self.y-y1)**2)**0.5 a = Point(3,4) print(a.distance(0,0))
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Round: pi = 3.14 def __init__(self, x, y, r): self.x = x self.y = y self.r = r def perimeter(self): return 2 * Round.pi * self.r def area(self): return Round.pi * self.r ** 2 def tangent(self, x1, y1, r1): if r1 + self.r != ((self.x - x1) ** 2 + (self.y - y1) ** 2) ** 0.5: return '两个圆不相切' else: return '两个圆相切' round = Round(0,0,2) print(round.perimeter()) print(round.area()) print(round.tangent(0,2,4))
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line: def __init__(self, start, end): self.start = start self.end = end def length(self): return abs(self.end - self.start) a = Line(5, 3) print(a.length())
day18-面向对象作业
最新推荐文章于 2024-03-06 19:44:34 发布