我们在计算机科学课上进行一项事件,我无法理解几行代码的含义。
这是初始代码(对于您可能需要的任何背景信息)。
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 调用的,但我不确定这些数字如何影响代码的其余部分。如果有人能帮我解释一下这最后几行代码,将不胜感激!
请您参考如下方法:
设置初始变量:
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
