I’m somewhat new to python, and have been searching for info on this all day. I want to be able to ask the user how many instances they want, and based on their input, create as many instances of a class as they requested.
I would also like to be able to have the name of each instance be based off of input such as asking the person’s name or something.
NumPlayers = input("How many people are playing? ")
for i in range(0, int(NumPlayers)-1):
name = input("What is your name? ")
name = Player()
This would be similar to John = Player() but “John” would be whatever name the user gave us, and there would be however many players the user wants.
From my research today, it seems that allowing people to determine the name of their own instances isn’t a good idea, so at this point I’m thinking something more along the lines of this:
NumPlayers = input("How many people are playing? ")
for i in range(0, int(NumPlayers)-1):
name = input("What is your name? ")
Player+i = Player(name)
This would be the same as Player1 = Player("John") etc. for more players. Is this something that is possible? It’s really stumping me. Just to clarify a few things, the class itself is already in the code, in the provided code Player is a class that has already been defined with methods and everything.
What you are looking for is a data structure, specifically, a list.
This will produce a list of
[Player(...), Player(...), ...]. This can be indexed (players[2]) or iterated over (for player in players:) among other operations. I recommend you read the documentation for more.As a side note, some lists can be constructed even more nicely with a list comprehension.