michael rogan
michael rogan

Reputation: 39

Python code to make multiple instances

Is there a way to make multiple instances of a class in python without having to type out the name for each instance? something like.

for i in range(10):
    i = some_class()

Is this possible? or am i just a huge noob.

Upvotes: 0

Views: 75

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

Use a dictionary:

d= {}

for i in range(10):
    d[i] = SomeClass()

If you just want to store a list of instances, use a list comprehension:

instances = [SomeClass() for _ in range(10)]

A list:

In [34]: class SomeClass():
        pass
   ....: 

In [35]: instances = [SomeClass() for _ in range(5)]

In [36]: instances
Out[36]: Out[41]: 
[<__main__.SomeClass at 0x7f559dcea0f0>,
 <__main__.SomeClass at 0x7f559dcea2e8>,
 <__main__.SomeClass at 0x7f559dcea1d0>,
 <__main__.SomeClass at 0x7f559dcea208>,
 <__main__.SomeClass at 0x7f559dcea080>])]

A dict where each i is the key and an instance is the value:

In [42]: d= {}

In [43]: for i in range(5):
   ....:         d[i] = SomeClass()
   ....:     

In [44]: d
Out[44]: 
{0: <__main__.SomeClass at 0x7f559d7618d0>,
 1: <__main__.SomeClass at 0x7f559d7617f0>,
 2: <__main__.SomeClass at 0x7f559d761eb8>,
 3: <__main__.SomeClass at 0x7f559d761e48>,
 4: <__main__.SomeClass at 0x7f559d7619e8>}

Upvotes: 2

Bonifacio2
Bonifacio2

Reputation: 3840

Yes. You just need a list to store your objects.

my_objects = []
for i in range(10):
    my_objects.append(some_class())

Upvotes: 2

Related Questions