以例子说明python的类、继承和多态

匿名 (未验证) 提交于 2019-12-02 22:54:36
##  1-10 1  class Player:  ## written by LiSongbo     def __init__(self,name):         self._name = name         self._score = 0     def reset_score(self):         self._score = 0     def incr_score(self):         self._score = self._score + 1     def get_name(self):         return self._name     def __str__(self):         return "name = %s,score=%s" % (self._name,self._score)     def __repr__(self):         return 'Player(%s)' % str(self)  class Human(Player):  ##  Player ,## written by LiSongbo     def __repr__(self):         return 'Human(%s)' % str(self)     def get_move(self):         while True:             try:                 n = int(input('%s move (1-10): ' % self.get_name()))                 if 1 <= n <= 10:                     return n                 else:                     print('0ops!')             except:                 print('0ops!')  import random class Computer(Player):  ##  Player,## written by LiSongbo     def __repr__(self):         return 'Computer(%s)' % str(self)     def get_move(self):         return random.randint(1,10)  def play_undercut(p1, p2): ## written by LiSongbo     p1.reset_score()     p2.reset_score()     m1 = p1.get_move()     m2 = p2.get_move()     print("%s move: %s" % (p1.get_name(), m1))     print("%s move: %s" % (p2.get_name(), m2))     if m1 == m2 - 1:         p1.incr_score()         return p1, p2, '%s wins!' % p1.get_name()     elif m2 == m1 - 1:         p2.incr_score()         return p1, p2, '%s wins!' % p2.get_name()     else:         return p1, p2, 'draw:no winner' # # c = Computer('Aobot') # h = Human('Rocky Lee') # x = play_undercut(c,h) # print(x) c1 = Computer('Aobot') ## written by LiSongbo c2 = Computer('Lisa') ## written by LiSongbo x1 = play_undercut(c1,c2) ## written by LiSongbo print(x1) print() h1 = Human('Rocky Lee') ## written by LiSongbo h2 = Human('Rocky') ## written by LiSongbo x2 = play_undercut(h1,h2) ## written by LiSongbo 

print(x2)


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!