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

发布于 2024-10-10 03:46:30 字数 366 浏览 3 评论 0原文

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

如果我有一个文本文件:

Sol
Centauri
Vega

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

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

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

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

I'm working on a game project.
I've created an object, Star(Object).
I want to assign the name of the variables, dynamically, from a text file.

If I have a text file with:

Sol
Centauri
Vega

I want the program to create the Star(Object) with variable names from the text file. I want the process automated, because I'm looking to create hundreds of stars.
I could write the code out by hand:

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

But isn't there a way to automate this?

Essentially, what I eventually want is a tuple with the list of stars, as their own objects. Then, when I am doing game maintenance, I can just iterate over all the objects in the tuple.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

携君以终年 2024-10-17 03:46:31

你的问题不清楚。由于您使用的是语法“Star(Centauri)”,这在 Python 中意味着您想要创建一个继承自 Centauri 的名为“Star”的类,这一事实使情况变得模糊。我认为你想要的可能是一个创建不同星星的工厂对象,但是你没有说出星星可能有何不同。据推测,差异在于位置,但您也没有说明如何处理。

根据猜测,最好的选择可能是将星型配置放入 YAML 文件中,并使用 pyYAML 加载它会返回一个可供您使用的 Python 数据结构。

Your question isn't clear. It's clouded by the fact that you're using syntax 'Star(Centauri)', which, in Python, means that you want to create a class called 'Star' that inherits from Centauri. I think what you want is probably a factory object that creates different stars, but then you don't say anything about how the stars might differ. Presumably, the difference is location, but you don't say how that's being handled either.

Best bet, based on guesses, might be to put your star configurations in a YAML file and use pyYAML to load it, which returns a Python data structure ready to go for you.

风吹短裙飘 2024-10-17 03:46:31
def makeStar(starName):
    globals()[starName] = Star(globals()[starName])
makeStar("Sol")

与“Sol”相同,

Sol = Star(Sol)

但“Sol”可以替换为任何字符串(例如从该文件读取的值)。

另外,您可能需要重新考虑创建这些全局变量 - 它会阻止您在需要时遍历所有星星,并且可能会导致命名冲突。如果您希望这些内容位于字典中,只需将“globals()”替换为您的字典名称即可。

def makeStar(starName):
    globals()[starName] = Star(globals()[starName])
makeStar("Sol")

is the same as

Sol = Star(Sol)

except "Sol" can be replaced with any string (eg the values read in from that file).

Also, you may want to rethink making these global variables - it prevents you from being able to iterate through all the stars, should you need to, and could possibly cause naming conflicts. If you want these to be in a dictionary, then just replace "globals()" with the name of your dictionary.

世态炎凉 2024-10-17 03:46:31

您可能应该为此使用字典。可以创建动态变量名称,但这没有意义,因为要访问,无论如何您都需要间接引用。

stars = {}
with open("stars.txt") as stars_file:
    for star_name in stars_file:
        star_name = star_name.strip()
        stars[star_name] = Star(star_name)

You probably should use a dictionary for that. It is possible to create dinamic variable names, but it would make no sense, since to access then you would need an indirect reference anyway.

stars = {}
with open("stars.txt") as stars_file:
    for star_name in stars_file:
        star_name = star_name.strip()
        stars[star_name] = Star(star_name)
吹梦到西洲 2024-10-17 03:46:31

您可以使用 types 模块在运行时创建类对象:

import types

def make_class(name):
    cls = types.ClassType(name, (), {})
    return cls

cls = make_class("Star")
obj = cls()

在上面的示例中,cls 成为您的 class Star

You can use the types module to create class objects at the run time:

import types

def make_class(name):
    cls = types.ClassType(name, (), {})
    return cls

cls = make_class("Star")
obj = cls()

In the above example, cls becomes your class Star

别闹i 2024-10-17 03:46:30

星号的名称不应该是变量的名称。变量名称应反映使用该变量的上下文,例如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

通过存储在字典中,您可以搜索特定的Starstars[name] 来遍历所有星星,或者使用 for s in Stars.values() 来迭代所有星星。

The name of a star should not be the name of the variable. Variable names should reflect the context in which the variable is used, e.g. destinationStar or homeStar.

A star's name should be a property of the Star object, accessed via 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

By storing in a dictionary, you can search for a particular Star with stars[name] or iterate over all the stars with for s in stars.values(), for example.

赤濁 2024-10-17 03:46:30

我想动态地分配变量的名称 这很好地表明您的设计完全错误。

很难确切地知道你的设计是什么,但我猜你想使用字典。

I want to assign the name of the variables, dynamically This is a very good indication that your design is completely wrong.

It's hard to know exactly what your design is, but I'm going to guess you want to use a dictionary instead.

如梦 2024-10-17 03:46:30
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)
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

and some sample data:

# 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  

then you can load your file like:

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

and

print s["Sol"]

results in

Sol is at (0.0, 0.0, 0.0)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文