Python面向对象设计:对象与类,继承————以大鱼吃小鱼为例

    科技2022-08-16  98

    前言

    编写类时,并非总是要从空白开始。如果要编写的类是另一个现成类的特殊版本,可使用继承。一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。当子类存在和父类一样的属性时,使用super() 函数用于调用父类。

    目录

    前言小游戏

    小游戏

    import random as r from matplotlib import pyplot as plt def randdirection(): a = r.random() if a>0.5: return 1 else: return -1 class fish: def __init__(self, name,x,y): self.name = name self.x=x self.y=y def move(self): if self.x<=0: self.x+=1 elif self.x>=5: self.x-=1 else: self.x -= randdirection() if self.y <= 0: self.y += 1 elif self.y>=5: self.y-=1 else: self.y -= randdirection() def getlocation(self): t=[self.x,self.y] return t class Goldfish(fish): pass class Carp(fish): pass class Salmon(fish): pass class Shark(fish): def __init__(self,name,x,y,cond): super().__init__(name,x,y) self.hungry=cond def eat(self): if self.hungry: print("吃货的梦想就是天天有的吃 ლ(´ڡ`ლ)好吃的.") self.hungry=0 return 1 else: print("太撑了,吃不下了!Zzzzzz") self.hungry = 1 return 0 fish=fish('鱼儿A',r.randint(1,5),r.randint(1,5)) goldfish=Goldfish('金枪鱼',r.randint(1,5),r.randint(1,5)) shark=Shark('鲨鱼',r.randint(1,5),r.randint(1,5),1) flaga=0 flagb=0 for i in range(300): plt.clf() plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签 plt.rcParams['axes.unicode_minus'] = False plt.title('大鱼吃小鱼') plt.xlim(0,5) plt.ylim(0,5) fish.move() goldfish.move() shark.move() t=[] t.append(fish.getlocation()) t.append(goldfish.getlocation()) t.append(shark.getlocation()) #print(t) _x=[t[0][0],t[1][0],t[2][0]] _y=[t[0][1],t[1][1],t[2][1]] plt.scatter(_x, _y, s=[20, 80, 400], c=[0.2, 0.4, 0.7]) if t[0][0]==t[2][0] and t[0][1]==t[2][1] and shark.eat(): flaga+=1 print('鱼儿A第{}次被鲨鱼吃掉了!'.format(flaga)) plt.savefig('鱼儿A第{}次被鲨鱼吃掉了.jpg'.format(flaga)) if t[1][0]==t[2][0] and t[1][1]==t[2][1] and shark.eat(): flagb+=1 print('金枪鱼第{}次被鲨鱼吃掉了!'.format(flagb)) plt.savefig('金枪鱼第{}次被鲨鱼吃掉了.jpg'.format(flagb)) if i==1: plt.savefig('大鱼吃小鱼.jpg') t.clear() plt.pause(0.01) if flagb==0 and flaga==0: print('(╥╯^╰╥)鲨鱼,没吃到鱼(T▽T)')

    输出结果为: 刚开始鱼的位置: 金枪鱼第1次被鲨鱼吃掉了 鱼儿A第1次被鲨鱼吃掉了

    Processed: 0.012, SQL: 9