Razinmore
Razinmore

Reputation: 13

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

Upvotes: 1

Views: 50

Answers (2)

Robert Seaman
Robert Seaman

Reputation: 2592

You're re-using the same Cell object. Create a new one every time instead.

Therefore, instead of doing:

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

Do this instead:

self.cell_list.append(Cell(0, 0, attr + str(x))

Another suggestion is to make the Cell object obtain it's own incremented ID:

class Cell(object):
    cell_ID = 0

    def __init__(self, x, y):
        Cell.cell_ID += 1
        self.cell_ID = 'cell{}'.format(Cell.cell_ID)
        self.x = x
        self.y = y

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

Then you can call as many as you want, and they'll all have a new ID:

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

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49330

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

Upvotes: 1

Related Questions