tags:

views:

111

answers:

4

How do I go about creating a list of objects (class instance) in Python?

Or is this a result of bad design? I need this cause I have different objects and I need to handle them at a later stage, so I would just keep on adding them to a list and call them later.

+3  A: 

The Python Tutorial discusses how to use lists.

Storing a list of classes is no different than storing any other objects.

def MyClass(object):
    pass

my_types = [str, int, float, MyClass]
Chris B.
+6  A: 

Storing a list of object instances is very simple

def MyClass(object):
    def __init__(number):
        self.number=number

my_objects = []

for i in range(100) :
    my_objects.append(MyClass(i))

#later

for obj in my_objects :
    print obj.number
yanjost
A: 

I think what you're of doing here is using a structure containing your class instances. I don't know the syntax for naming structures in python, but in perl I could create a structure obj.id[x] where x is an incremented integer. Then, I could just refer back to the specific class instance I needed by referencing the struct numerically. Is this anything in the direction of what you're trying to do?

Andrew
+1  A: 

In Python, the name of the class refers to the class instance. Consider:

class A: pass
class B: pass
class C: pass

lst = [A, B, C]

# instantiate second class
b_instance = lst[1]()
print b_instance
A. Jesse Jiryu Davis