1

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.

2 Answers 2

14

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.

0
6

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()
1
  • It's better to use a list comprehension, but this solution is correct.
    – jathanism
    Sep 12, 2011 at 21:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.