python - 我可以在 Python 2.7 中从文本文件创建对象名称吗?

标签 python object python-2.x

我正在从事一个游戏项目。 我创建了一个对象,Star(Object)。 我想从文本文件中动态分配变量的名称。

如果我有一个文本文件:

Sol
Centauri
Vega

我希望程序使用文本文件中的变量名创建 Star(Object)。我希望这个过程自动化,因为我希望创造数百颗星星。 我可以手写代码:

Sol = Star(Sol)
Centauri = Star(Centauri)
Vega = Star(Vega)

但是有没有办法自动执行此操作?

本质上,我最终想要的是一个包含星星列表的元组,作为它们自己的对象。然后,当我进行游戏维护时,我可以迭代元组中的所有对象。

最佳答案

星星的名字不应该是变量的名字。变量名称应反射(reflect)变量使用的上下文,例如destinationStarhomeStar

星星的名字应该是 Star 对象的一个​​属性,通过 Star.name 访问:

class Star(object):
    """Keeps track of a star."""

    def __init__(self, starName):
        self.name = starName

    # other methods...

def read_stars(filename):
   # oversimplified:
   stars = {}
   starfile = open(filename, "r")
   for line in starfile:
      words = line.split()
      if len(words) == 2 and words[0] == 'star':
          name = words[1]
          stars[name] = Star(name)
   return stars

通过存储在字典中,您可以使用 stars[name] 搜索特定的 Star 或使用 for s in stars 遍历所有星星。例如,values()

关于python - 我可以在 Python 2.7 中从文本文件创建对象名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4576987/

相关文章:

python - Sphinx LaTeX 标记限制

java - 如何在 Java 中复制对象?

python - Unicode 到字符串 Python 2

python - json与python中另一个json的递归比较

具有灵活数组成员的 Python ctypes 结构到 bytearray

python - Google Colaboratory 中的错误 - AttributeError : module 'PIL.Image' has no attribute 'register_decoder'

python - 让 PyC​​harm 导入 sklearn

python - 为什么python以乱码字符写入文件

php - array_multisort 具有多维对象数组

class - 引用 PowerShell 类中另一个属性的属性