如何在python中创建对象的无限迭代?

2024-09-30 06:21:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在尝试创建一个程序来测试对象创建的一些方法。目前,我正在编写一个程序,它包括创建对象,给它们一个唯一的数值变量,并将它们分配给一个列表,以便将来引用。以下是我为创建变量名而编写的:

def getRectangleName():
    rectName = list("Rectangle")
    SPAWNEDOBJECTLIST.append(len(SPAWNEDOBJECTLIST))
    rectName.append(str(len(SPAWNEDOBJECTLIST)))
    return rectName

然后把它传递给某个东西,把这个字符串变成一个变量名。我尝试了eval(),了解到由于某种原因这是不好的,但它无论如何也不起作用,并尝试了一些变通方法,但没有效果。在

我想有很多游戏在屏幕上有无限数量的字符。有没有一种既定的方法可以对这样的对象进行迭代?在

对象本身有一个X和Y,因此它们可以作为在屏幕上显示矩形的参考点(未来的想法是让每个对象自己移动,所以简单地列出X和Y来绘制矩形是没有用的)。在

编辑:问题是我不知道如何给每个对象一个自己的变量,以便将来引用。在

Edit2:实际上,我认为我没有问对问题,也没有使用正确的术语。我需要能够有一个无限数量的对象创建后,程序已经运行,并能够单独引用他们。在


Tags: 对象方法程序列表数量len屏幕def
2条回答

The problem is that I don't know how to give each object its own variable to put it on a list for future referencing.

当你认为你需要你没有输入到你的程序中的变量时,你就错了。不需要为变量赋值就可以将其放入列表中:

x = [1, 2, 3]                 # Note how I don't assign 1, 2, or 3 to variables.
x.append(4)                   # 4 doesn't get a variable either.
x.append(make_a_rectangle())  # We create a rectangle and stick it on the list.
do_stuff_with(x[4])           # We pass the rectangle to a function.

x = []                            # New list.
for i in xrange(n):
    x.append(make_a_rectangle())  # This happens n times.
# At this point, we have n rectangles, none of them associated with their own
# variable, none of them with a name.

如果你认为你需要事物的名称(通常情况下,你并不真的需要这些名称),你可以使用dict:

^{pr2}$

如果您想动态地创建变量并将它们添加到类实例中,请使用

class MainClass:
    def __setattr__(self, name, value):
        self.__dict__[name] = value

def getRectangleNameGenerator(N = 10):
    X = 0
    while X <= N:
        X += 1
        yield "Rectangle" + str(X)
RectangleName = getRectangleNameGenerator()

ClassInstances = {next(RectangleName) : MainClass}
ClassInstances[next(RectangleName)] = MainClass

ClassInstances["Rectangle1"].Temp = 10
print ClassInstances["Rectangle1"].Temp

如果这个班只有X和Y

^{pr2}$

相关问题 更多 >

    热门问题