-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog: def __init__(self, name, gender, kinds): self.name = name self.gender = gender self.kinds = kinds def action(self): return '叫唤' def __repr__(self): return f'狗名字:{self.name} 狗性别:{self.gender} 狗品种:{self.kinds} 动作:{self.action()}' d1 = Dog('旺财', '公狗', '柴犬') print(d1) class Person: def __init__(self, man_name, age, dog): self.man_name = man_name self.age = age self.dog = dog def man_action(self): return '遛狗' def __repr__(self): return f'人的名字:{self.man_name} 人的年龄:{self.man_name} 人的狗:{self.dog} 动作:{self.man_action()}' p1 = Person('小明', 20, '旺财') print(p1)
-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Juxing: def __init__(self, c, k): self.c = c self.k = k def zhou(self): return self.c * 2 + self.k * 2 def mian(self): return self.c * self.k def __repr__(self): return f'长为:{self.c},宽为:{self.k},面积为:{self.mian()},周长为:{self.zhou()}' p1 = Juxing(2,3) print(p1)
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point: def __init__(self, x, y): self.X = x self.Y = y def distance(self,point2): return ((self.X - point2.X) ** 2 + (self.Y - point2.Y) ** 2) ** 0.5 p1 = Point(4, 3) p2 = Point(0,0) print(p1.distance(p2))
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
class Circle: pi = 3.14 def __init__(self, r, o): self.R = r self.O = o def girth(self): return self.pi * self.R * 2 def area(self): return self.pi * self.R ** 2 def circumscribed(self, circle2): if ((self.O[0] - circle2.O[0]) ** 2 + (self.O[1] - circle2.O[1]) ** 2) ** 0.5 == self.R + circle2.R: return 'True' else: return 'False' c1 = Circle(1, (0, 0)) c2 = Circle(1, (0, 2)) print(c1.circumscribed(c2))
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line: def __init__(self, o): self.O = o def lenth(self, point2): return ((self.O[0] - point2.O[0]) ** 2 - (self.O[1] - point2.O[1]) ** 2) ** 0.5 o1 = Line((1, 0)) o2 = Line((3, 0)) print(f'两点形成的线段长为:{o1.lenth(o2)}')
-
写一个斗地主游戏类(根据生活经验添加类的内容)
import random # 发牌器 class Game: list1 = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] * 4 + ['大王', '小王'] def person1(self): return random.sample(self.list1, 27) p1 = Game() p2 = Game() print(p1.person1()) print(p2.person1())
day14-面向对象
于 2022-08-04 19:55:50 首次发布