gpt4 book ai didi

python - 您可以使用函数生成具有唯一成员的类的实例吗?

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:40 24 4
gpt4 key购买 nike

我正在尝试生成一个对象的 100 个实例,每个实例都有一个编号的 ID 成员。当我运行这个程序时,我期望它生成 100 个具有 cell_ID(例如 cell1、cell2、cell3 等)的 Cell 类实例。但是,我收到一个属性错误,告诉我 Cell 实例没有调用 方法。我真的不知道我想做的事情是否可行,而且我在网上找不到有关此主题的任何内容。感谢您花时间阅读本文,我真的很感激。

import string
class Cell():
def __init__(self, x, y, cell_ID):
self.x = x
self.y = y
self.cell_ID = cell_ID
def __str__(self):
return "%s:(%i,%i)" % (self.cell_ID, self.x, self.y,)

class Event(Cell):
def __init__(self):
print "EVENT TEST"
self.cell_list = []

def makeCells(self, obj, attr):
for x in range(0,100):

obj().attr = attr + str(x)
self.cell_list.append(obj)


e = Event()
e.makeCells(Cell(0,0, ""), "cell")

最佳答案

不要这样做。使用诸如列表之类的数据结构。

import string

class Cell():
def __init__(self, x, y, cell_ID):
self.x = x
self.y = y
self.cell_ID = cell_ID

def __str__(self):
return "%s:(%i,%i)" % (self.cell_ID, self.x, self.y,)

l = [Cell(0, 0, id) for id in range(100)]

关于python - 您可以使用函数生成具有唯一成员的类的实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com