Razinmore Razinmore - 7 months ago 12
Python Question

Can you generate instances of a class with unique members using a function?

I'm trying to generate 100 instances of an object, each with a numbered ID member. When I run this, I was expecting it to generate 100 instances of the Cell class with cell_IDs such as cell1, cell2, cell3, etc. However, I get an attribute error telling me that the Cell instance has no call method. I don't really know if what I want to do is possible, and I can't find anything online about this topic. Thank you for taking the time to read this, I really appreciate it.

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")

Answer

Do not do that. Use a data structure such as a list.

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)]