2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

It's better to use a list comprehension, but this solution is correct.

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.