<p>使用类!!你知道吗</p>
<pre><code>class TennisPlayer(object):
def __init__(self,name,wins=0,games_played=0,win_pct=None):
self.name = name
self.wins = wins
self.games_played = games_played
# Note that although I do take win_pct as a parameter, I never use
# it anywhere. This trick may be useful for you if you end up maintaining
# code someone else has written and don't need part of their data
# structure anymore, but don't feel like refactoring code is worth the time
@property
def win_pct(self):
return self.wins/self.games_played
# as per lanzz, the @property token basically makes this a function that can
# be called like an instance variable.
#
# >>> player = TennisPlayer("Foo Bar",2,3) # 2 wins 1 loss
# >>> player.win_pct
# 0.6666666666666666
#
# You could probably make this prettier using string formatting.
# Something like return "{:.2f}%".format(self.wins/self.games_played*100)
# but it will make data manipulation much harder. Consider writing
# a TennisPlayer.print_stats() function that will just pretty print
# all the stats to stdout
def win_game(self,other):
self.games_played += 1
self.wins += 1
other.games_played +=1
lst = [['B Borg', '3', '3', '1.0'], ['F Perry', '7', '8', '0.875'], ['R Nadal', '3', '5', '0.6']]
tennisplayers = [TennisPlayer(*player) for player in lst]
# randomly choose B Borg (tennisplayers[0]) and F Perry (tennisplayers[1])
tennisplayers[0].win_game(tennisplayers[1])
</code></pre>
<p>这方面的实现有你所能想象的那么多。最好的方法(在我看来,无论如何)是实现一个<code>TennisMatch</code>类:</p>
<pre><code>class TennisMatch(object):
def __init__(self,player1,player2):
if type(player1) == list:
# implement special handlers for doubles games
else:
self.player1 = player1
self.player2 = player2
def play_match(self):
# do some stuff here
# to determine who wins and
# who goes crying to mommy
for player in [player1,player2]:
if player == winner: player.wins += 1
player.games_played += 1
</code></pre>
<p>然后您可以忽略我放在<code>TennisPlayer</code>类中的<code>def win_game</code>,因为它实际上只是一个实现较差的setter。这样效果更好。你知道吗</p>