Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating instances in a loop with different variables

Tags:

python

I'm tring to create class instances in a loop. All instances need to be assinged to a different variable. These variables can be a sequence of letters like [a,b,c].

class MyClass(object):
    pass

for i in something:
    #create an instance

If the loop turns 3 times, I want the loop make something like that:

a = MyClass()
b = MyClass()
c = MyClass()

Is there a way to do that?

like image 833
Hzyf Avatar asked Dec 09 '22 00:12

Hzyf


1 Answers

Using independent variable names this way is a bit odd; using either a dict or a list, as shown above, seems better.

Splitting it down the middle, how about

a,b,c = (MyClass() for _ in range(3))
like image 163
Hugh Bothwell Avatar answered Feb 04 '23 15:02

Hugh Bothwell