Solution Review 2: Implementing a Sports Team!
This lesson provides and explains the solution to the challenge, "Implementing a Sports Team!"
We'll cover the following...
Solution #
Press + to interact
class Player:def __init__(self, ID, name, teamName):self.ID = IDself.name = nameself.teamName = teamNameclass Team:def __init__(self, name):self.name = nameself.players = []def getNumberOfPlayers(self):return len(self.players)def addPlayer(self, player):self.players.append(player)class School:def __init__(self, name):self.name = nameself.teams = []def addTeam(self, team):self.teams.append(team)def getTotalPlayersInSchool(self):length = 0for n in self.teams:length = length + (n.getNumberOfPlayers())return lengthp1 = Player(1, "Harris", "Red")p2 = Player(2, "Carol", "Red")p3 = Player(1, "Johnny", "Blue")p4 = Player(2, "Sarah", "Blue")red_team = Team("Red Team")red_team.addPlayer(p1)red_team.addPlayer(p2)blue_team = Team("Blue Team")blue_team.addPlayer(p2)blue_team.addPlayer(p3)mySchool = School("My School")mySchool.addTeam(red_team)mySchool.addTeam(blue_team)print("Total players in mySchool:", mySchool.getTotalPlayersInSchool())
-
Line 2 – 5: Defined initializer for
Player
-
Line 9 – 11: Defined initializer for
Team
, which also contains a list ofplayers
-
Line 13 – 14: ...