以例子说明python的类、继承和多态.docx
- 文档编号:176315
- 上传时间:2022-10-05
- 格式:DOCX
- 页数:2
- 大小:8.23KB
以例子说明python的类、继承和多态.docx
《以例子说明python的类、继承和多态.docx》由会员分享,可在线阅读,更多相关《以例子说明python的类、继承和多态.docx(2页珍藏版)》请在冰豆网上搜索。
##游戏规则:
两个玩家同时选择一个1-10的整数,如果一个玩家选择的整数比对方的小
1,则该玩家获胜,否则算平手。
classPlayer:
##writtenbyLiSongbodefinit(self,name):
self._name=nameself._score=0
defreset_score(self):
self._score=0
defincr_score(self):
self._score=self._score+1defget_name(self):
returnself._namedefstr(self):
return"name=%s,score=%s"%(self._name,self._score)
defrepr(self):
return'Player(%s)'%str(self)
classHuman(Player):
##第一个子类,继承了类Player,##writtenbyLiSongbodefrepr(self):
return'Human(%s)'%str(self)defget_move(self):
whileTrue:
try:
n=int(input('%smove(1-10):
'%self.get_name()))
if1<=n<=10:
returnn
else:
except:
print('0ops!
')
print('0ops!
')
importrandom
classComputer(Player):
##第二个子类,继承了类Player,##writtenbyLiSongbodefrepr(self):
return'Computer(%s)'%str(self)defget_move(self):
returnrandom.randint(1,10)
defplay_undercut(p1,p2):
##writtenbyLiSongbop1.reset_score()
p2.reset_score()
m1=p1.get_move()m2=p2.get_move()
print("%smove:
%s"%(p1.get_name(),m1))print("%smove:
%s"%(p2.get_name(),m2))ifm1==m2-1:
p1.incr_score()
returnp1,p2,'%swins!
'%p1.get_name()elifm2==m1-1:
p2.incr_score()
returnp1,p2,'%swins!
'%p2.get_name()
else:
#
returnp1,p2,'draw:
nowinner'
#c=Computer('Aobot')#h=Human('RockyLee')#x=play_undercut(c,h)#print(x)
c1=Computer('Aobot')##writtenbyLiSongboc2=Computer('Lisa')##writtenbyLiSongbo
x1=play_undercut(c1,c2)##writtenbyLiSongboprint(x1)
print()
h1=Human('RockyLee')##writtenbyLiSongboh2=Human('Rocky')##writtenbyLiSongbo
x2=play_undercut(h1,h2)##writtenbyLiSongboprint(x2)
————————————————
版权声明:
本文为CSDN博主「顶洞达人」的原创文章,遵循CC4.0BY-SA版权协议,转载请附上原文出处链接及本声明。
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 例子 说明 python 继承