0

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.

0

2 Answers 2

2

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

my_objects = []
for i in range(10):
    my_objects.append(some_class())
Sign up to request clarification or add additional context in comments.

Comments

2

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>}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.