-
定义一个狗类和一个人类:
狗拥有属性:姓名、性别和品种 拥有方法:叫唤
人类拥有属性:姓名、年龄、狗 拥有方法:遛狗
class Dog: def __init__(self,name,gender,type): self.name = name self.gender = gender self.type = type def woof(self): print(f'一只叫做{self.name}的{self.gender}{self.type}在汪汪汪') class Human: def __init__(self,name,age,dog): self.name = name self.age = age self.dog = dog def walk_dog(self): print(f'{self.age}的{self.name}遛着{self.dog}狗') dog1 = Dog('花花','公','吉娃娃') human1 = Human('小刘',55,dog1.name) dog1.woof() human1.walk_dog()
-
定义一个矩形类,拥有属性:长、宽 拥有方法:求周长、求面积
class Rectangle: def __init__(self,length,width): self.length = length self.width = width def perimeter(self): return (self.width + self.length) * 2 def area(self): return self.width * self.length
-
定义一个二维点类,拥有属性:x坐标、y坐标 拥有方法:求当前点到另外一个点的距离
class Point: x1= 10 y1= 20 def __init__(self,x , y): self.x =x self.y = y def distance(self): return ((self.x - Point.x1) ** 2 + (self.y - Point.y1) ** 2) ** 0.5
-
定义一个圆类,拥有属性:半径、圆心 拥有方法:求圆的周长和面积、判断当前圆和另一个圆是否外切
from math import pi class Circle: radius1 = 5 x1 = 45 y1 = 56 def __init__(self,radius,x,y): self.radius = radius self.x = x self.y = y def perimeter(self): return 2 * pi * self.radius def area(self): return self.radius * pi ** 2 def circumscribe(self): if ((self.x - Circle.x1) ** 2 + (self.y - Circle.y1) ** 2) ** 0.5 == self.radius + Circle.radius1: return '外切' else: return '不外切'
-
定义一个线段类,拥有属性:起点和终点, 拥有方法:获取线段的长度
class Line: def __init__(self,x1,y1,x2,y2): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 def distance(self): dis = ((self.x1 - self.x2) ** 2 + (self.y1 - self.y2) ** 2) ** 0.5 return dis
-
写一个斗地主游戏类(根据生活经验添加类的内容)
from random import shuffle,choice class FightLords: all_card = [] sort1 = {'3':1,'4' :2,'5':3,'6':4,'7':5,'8':6,'9':7,'10':8,'J':9,'Q':10,'K':11,'A':12,'2':13,'ing':14,'ING':15} for x in [str(y) for y in range(2,11)] + ['J','Q','K','A']: for z in ['♥','♦','♠','♣']: all_card.append(z+x) all_card.extend(['KING','king']) def __init__(self): self.player1 = [] self.player2 = [] self.player3 = [] def deal(self): shuffle(FightLords.all_card) left_card = FightLords.all_card[-1:-4:-1] lord_card = choice(FightLords.all_card[:51]) all_card = iter(FightLords.all_card) for x in range(17): self.player1.append(next(all_card)) self.player2.append(next(all_card)) self.player3.append(next(all_card)) self.player1.sort(key=lambda item: FightLords.sort1[item[1:]],reverse=True) self.player2.sort(key=lambda item: FightLords.sort1[item[1:]],reverse=True) self.player3.sort(key=lambda item: FightLords.sort1[item[1:]],reverse=True) if lord_card in self.player1: return f'地主:{self.player1},农民1:{self.player2},农民2{self.player3},地主牌:{left_card}' elif lord_card in self.player2: return f'地主:{self.player2},农民1:{self.player1},农民2{self.player3},地主牌:{left_card}' else: return f'地主:{self.player3},农民1:{self.player2},农民2{self.player1},地主牌:{left_card}' f1 = FightLords() print(f1.deal())
day17-面向对象作业
最新推荐文章于 2023-07-19 17:09:58 发布