Reputation: 365
i have a class "karte" i want to know is there a way of dynamic name creation of my new objects normal object creation would be
karta=karte()
but i am curious in something like this
karta[i]=karte()
or something like that where i would be the number of for loop. and at the end i would call object like this
karta1.boja
karta2.boja
karta3.boja
how can i achieve that , im new to python thanks.
Upvotes: 2
Views: 22207
Reputation: 10080
You can create a list of objects like this:
karta = []
for i in range(10):
karta.append(karte())
Or using a list comprehension:
karta = [karte() for i in range(10)]
Now you can access the objects like this: karta[i]
.
To accomplish your last example, you have to modify the globals()
dictionary. I do not endorse this at all, but here is how to do it:
g = globals()
for i in range(10):
g["karte" + str(i)] = karte()
This is not very pythonic though, you should just use a list.
Upvotes: 14
Reputation: 1602
Unless you have a real need to keep the objects out of a list and have names like karta1, karta2, etc. I would do as you suggest and use a list with a loop to initialize:
for i in some_range:
karta[i]=karte()
Upvotes: 6