0

I need to create several hundred instances of an Object (rack) but i can't find the proper way to write this in. What i need is something like this but more elegant:

class Rack:

    def __init__(self):
        self._listeMedNoder = []

Rack1 = Rack()

Rack2 = Rack()

Rack3 = Rack()

etc... but up to say 100.

2 Answers2

1

The best way to do this is by creating a List instance, and filling that with your objects.

racks = []
for _ in range(n):
    racks.append(Rack)

Where n = the amount of instances you want to create. Note that range() is exclusive, so you'll have to increase it by 1 to create enough instances of Rack. To access the classes you can call racks[index] where the index is the class you want to access. Note that lists start from index '0', so racks[1] will be the second element (in this case, the second class).

Mek-OY
  • 54
  • 4
0

Do you need to name them? If not, just make a list:

racks = [Rack() for _ in range(100)]

You can then access any instance of Rack using the list index:

print racks[0]
101
  • 8,514
  • 6
  • 43
  • 69