0

I'm trying to create 3 different teams with 3 different players on each team. But right now all the players on each team are the same. Below is the code I have. If anyone has a solution that would be great.

class player():
    name=''

class team():
    name=''
    players=[]

teams=[]

for i in range (3):
    teams.append(team())
    teams[i].name=str(i)
    for j in range(3):
        teams[i].players.append(player())
        teams[i].players[j].name='P'+str(i)+str(j)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    Do you want each instance of the player class to have a different name, or one name for all of the players? I think a [tutorial on classes](https://docs.python.org/3/tutorial/classes.html#classes) would help. – tdelaney Aug 11 '20 at 20:51

1 Answers1

1

You can't just assign a value to an attribute of the class in the root definition. This will set the attribute for all instances of the class. Use the constructor (__init__() method) to assign values to attributes and then change them:

    class player():
        def __init__(self):
            self.name=''

    class team():
        def __init__(self):
            self.name=''
            self.players=[]

This way each player and each team gets its own name attribute and each team their own list of players.

You can also accept arguments in the __init__() method to name the team and player directly:

    class player():
        def __init__(self,playername=''):
            self.name=playername

    p = player("Jim")

This will initiate a player who already has the .name attribute set to "Jim".

Martin Wettstein
  • 2,771
  • 2
  • 9
  • 15
  • Wouldn't you include `name` in the initializer? – tdelaney Aug 11 '20 at 20:52
  • I personally would, yes. I'm notorious for long parameter lists in initializers. But that's a matter of taste, I think. – Martin Wettstein Aug 11 '20 at 20:56
  • It's also worth including `players` as a parameter to `team.__init__()`. OP could then get the user code down to a single line if they wanted: `teams = [team(str(i), [player(f'P{i}{j}' for j in range(3)]) for i in range(3)]` – wjandrea Aug 11 '20 at 21:00
  • Possible. But I don't think OP worries too much about code golf at this moment. – Martin Wettstein Aug 11 '20 at 21:09