-1

So I got the following problem. Let's say I want to make a game and therefore I have a list of players. To work with this players and give them several attributes I create a Players class. Now I want to automatically paste every player in my list as a separate instance in my Players class.

class Players:
    def __init__(self, name):
        self.player_name = name


players_arr = ['Testplayer1', 'Testplayer2', 'Testplayer3']


# Testplayer1 = Players(name = players_arr[0])
# Testplayer2 = Players(name = players_arr[1])
# Testplayer3 = Players(name = players_arr[2])

Any idea how I could automate the process commented out? I basicly want to create this class because everyone has a counter (imagine like a death counter) and of course it has to tick separately.

martineau
  • 119,623
  • 25
  • 170
  • 301

4 Answers4

1

Try comprehension list:

Testplayer = [Players(p) for p in players_arr]
Testplayer

Output: [<__main__.Players at 0x14225308438>,
        <__main__.Players at 0x14225308ba8>,
        <__main__.Players at 0x14225308be0>]
Marios
  • 26,333
  • 8
  • 32
  • 52
0
class Players:
    
    def __init__(self, name):
        self.player_name = name


players_arr = ['Testplayer1', 'Testplayer2', 'Testplayer3']
players_objs = []
for player in players_arr :
    players_objs.append(Players(name = player))
abdulsaboor
  • 678
  • 5
  • 10
0

You can use globals() dictionary which is responsible for your namespace.

for n in players_arr:
    globals()[n] = Players(n)
print(Testplayer1, Testplayer2, Testplayer3) #checking if it works

However, this is not advised. Using comprehensions is a better solution.

mathfux
  • 5,759
  • 1
  • 14
  • 34
0

First, I recommend that you name your class in the singular: Player. The class defines a single player.

If you need merely a tractable sequence of player objects, then create them with a simple list comprehension:

player_name = ['Testplayer1', 'Testplayer2', 'Testplayer3']
player_objs = [Player() for _ in len(player_arr)]

However, if you do need the players associated with a regular sequence of names, then use a dict, and build the names as you iterate:

player_table = {"TestPlayer" + str(i) : Player() for i in range(n)}

Where n is the quantity of players you want.

Prune
  • 76,765
  • 14
  • 60
  • 81