Dynamically instantiate Player class in a loop
I am making a simple Python game. I have a text file with the following on each line:
player name, player IP, player health, player items
I have a loop which goes through each line in the file and get the variables for each player (each line in the text file is a player).
I have a class called Player
, I need on开发者_开发技巧e instance of this for each player.I wish to have a list which contains all the instances of Player.
Sven has a good answer but you can even do away with the first line and just do
config = [line.split(',') for line in open("config")]
Or as you may want to actually instantiate the players:
config = [Player(line.split(',')) for line in open("config")]
If you're going to be doing a lot more csv configs for your game, look into the csv module.
What you need to do is use the map function to call the constructor and expand what you've read in the config file as the parameters of the instantiation:
players = map(lambda tuple_args: Player(*tuple_args), (line.split(',') for line in open("config")))
or simpler using list comprehension:
players = [Player(*(line.split(','))) for line in open("config")]
精彩评论