简体   繁体   English

在循环中动态实例化Player类

[英]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.

相关问题 使用 locate 动态实例化类 - Instantiate class dynamically with locate 如何在python中动态实例化类? - How to instantiate class in python dynamically? 在循环或if语句中实例化类是否在编程上是正确的? - Is it programmatically correct to instantiate a class inside a loop or an if statement? Python 3.9 如果一个字符串匹配一个class的名字,实例化class(动态实例化具体的class) - Python 3.9 if a string matches a class name, instantiate the class (instantiate a specific class dynamically) 动态实例化python类的对象类似于PHP new $ classname? - Dynamically instantiate object of the python class similar to PHP new $classname? 如何动态地知道和实例化在 Python 模块中实现的一个 class - How to know and instantiate only one class implemented in a Python module dynamically 在Python中动态实例化类 - dynamically instantiate classes in Python Python 在循环中动态访问 class 的功能 - Python dynamically access features of class in loop 在这个例子中,如何动态实例化(通过classname作为字符串)类来调用getThings()? - How can I dynamically instantiate (by classname as a string) the class to call getThings() in this example? 如何动态实例化其构造函数带有多个参数的类? - How do I dynamically instantiate a class whose constructor takes multiple parameters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM