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

1 投票
7 回答
2532 浏览
提问于 2025-04-16 09:17

我正在做一个游戏项目。

我创建了一个对象,叫做星星(Star)。

我想从一个文本文件中动态地给这些对象的变量命名。

假设我有一个文本文件,里面写着:

Sol
Centauri
Vega

我希望程序能根据文本文件里的内容来创建星星对象,并给它们命名。我想让这个过程自动化,因为我打算创建几百颗星星。

我可以手动写出代码:

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

但是有没有办法让这个过程自动化呢?

简单来说,我最终想要的是一个包含所有星星的元组,每颗星星都是一个独立的对象。这样在我维护游戏的时候,就可以方便地遍历这个元组里的所有对象。

7 个回答

1
class BadStar(Exception): pass

class Star(object):
    def __init__(self, name, mass, mag, color, x, y, z):
        self.name = name
        self.mass = float(mass)
        self.mag = float(mag)
        self.color = color
        self.pos = (float(x),float(y),float(z))

    @classmethod
    def fromstr(cls, s):
        "Alternate constructor from string"
        stardata = [i.strip() for i in s.split(',')]
        if len(stardata)==7:
            return cls(*stardata)
        else:
            raise BadStar("wrong number of arguments in string constructor")

    def __str__(self):
        x,y,z = self.pos
        return "{0} is at ({1}, {2}, {3})".format(self.name, x, y, z)

class StarIndex(dict):
    def load(self, fname):
        "Load stars from text file"
        with open(fname, "r") as f:
            for line in f:
                line = line.split('#')[0]   # discard comments
                line = line.strip()         # kill excess whitespace
                if len(line):               # anything left?
                    try:
                        star = Star.fromstr(line)
                        self[star.name] = star
                    except BadStar:
                        pass                # discard lines that don't parse
        return self

还有一些示例数据:

# Name,           Mass, Absolute Magnitude, Color,     x,      y,      z
#
# Mass is kg
# Color is rgb hex
# x, y, z are lightyears from earth, with +x to galactic center and +z to galactic north
Sol,              2.0e30, 4.67,             0xff88ee,  0.0,    0.0,    0.0
Alpha Centauri A, 2.2e30, 4.35,             0xfff5f1, -1.676, -1.360, -3.835  

然后你可以像这样加载你的文件:

s = StarIndex().load("stars.txt")

还有

print s["Sol"]

结果是

Sol is at (0.0, 0.0, 0.0)
1

我想动态地给变量命名。

这说明你的设计思路可能完全不对。

虽然我不太清楚你的设计具体是什么,但我猜你可能更适合使用字典。

4

星星的名字不应该用作变量的名字。变量的名字应该能反映出它的使用场景,比如可以用 destinationStar(目标星星)或者 homeStar(家乡星星)这样的名字。

星星的名字应该是 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() 来遍历所有的星星。

撰写回答