[英]Dynamically instantiate Player class in a loop
I am making a simple Python game. 我正在做一个简单的Python游戏。 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 one instance of this for each player.I wish to have a list which contains all the instances of Player. 我有一个名为
Player
的类,每个播放Player
需要一个实例。我希望有一个包含Player的所有实例的列表。
Sven has a good answer but you can even do away with the first line and just do Sven有一个很好的答案,但是您甚至可以删除第一行,然后做
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. 如果您要为游戏做更多的csv配置,请查看csv模块。
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: 您需要做的是使用map函数调用构造函数,并将您在配置文件中读取的内容扩展为实例化的参数:
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")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.