这些代码行做了什么? (运动模拟)

时间:2015-12-14 16:59:30

标签: python object methods parameters arguments

我们正在计算机科学课上开展一项活动,而且我无法理解几行代码的含义。

以下是初始代码(适用于您可能需要的任何背景信息)。

class SportsMatch(object):
     def __init__(self, teamA="Team A", teamB="TeamB"):
          self.teamA = teamA
          self.scoreA = 0
          self.teamAScorePoints = 1

          self.teamB = teamB
          self.scoreB = 0
          self.teamBScorePoints = 1

     def setScorePoints(self, teamAScorePoints=1, teamBScorePoints=1):
          self.teamAScorePoints = teamAScorePoints
          self.teamBScorePoints = teamBScorePoints

     def whoWins(self):
          if (self.scoreA < self.scoreB):
               print(self.teamB+" win the game!")
          elif (self.scoreA > self.scoreB):
               print(self.teamA+" win the game!")
          else:
               print("Tie score")

     def teamAScores(self):
          self.scoreA = self.scoreA + self.teamAScorePoints

     def teamBScores(self):
          self.scoreB = self.scoreB + self.teamBScorePoints

然后,我们应该考虑以下代码并找出每行代码的作用:

s = SportsMatch("Chargers", "Raiders")
s.setScorePoints(1, 2)
s.teamAScores()
s.teamBScores()
s.teamAScores()
s.teamBScores()
s.whoWins()

我有一种普遍的理解,但我的老师希望我们更具体。我也理解第二行是用参数1和2调用的,但是我不确定这些数字如何与其余的代码相匹配。如果有人能帮我解释这几行代码,我们将不胜感激!

2 个答案:

答案 0 :(得分:3)

设置初始变量:

self.teamX = teamX        # setting name
self.scoreX = 0           # initial score
self.teamAXcorePoints = 1 # score increment

这两个是分数增量:

self.teamAScorePoints = 1
self.teamBScorePoints = 1

此处用于增加每个球队的得分:

def teamAScores(self):
    self.scoreA = self.scoreA + self.teamAScorePoints
def teamBScores(self):
    self.scoreB = self.scoreB + self.teamBScorePoints

现在流程:

s = SportsMatch("Chargers", "Raiders") # defining the match
s.setScorePoints(1, 2)                 # setting initial score increments
s.teamAScores()                        # team A scores 1 point
s.teamBScores()                        # team B scores 2 points
s.teamAScores()                        # team A scores another 1 point
s.teamBScores()                        # team B scores another 2 points
s.whoWins()                            # prints winner

答案 1 :(得分:2)

代码的一般描述:

s = SportsMatch("Chargers", "Raiders")

这行代码调用__init__类中的SportsMatch方法,并传递方法“Chargers”和“Raiders”。然后将这些保存为运动队的名称。

s.setScorePoints(1, 2)

此行调用类中的setScorePoints方法并将其传递给12。这些值保存为每个球队得分在得分时增加的数量。

s.teamAScores()
s.teamBScores()
s.teamAScores()
s.teamBScores()

这些行调用teamAScoresteamBScores方法。这些方法根据调用的方法增加团队的分数。

s.whoWins()

这会调用班级的whoWins方法,比较团队得分并打印获胜团队。

获胜团队将是B队,也称为Raiders。 B队的得分为4,A队的得分为2