52

Suppose you have to create 10 class objects in python, and do something with them, like:

obj_1 = MyClass()
other_object.add(obj_1)
obj_2 = MyClass()
other_object.add(obj_2)
.
.
.
obj_10 = MyClass()
other_object.add(obj_10)

How would you do it with a loop, and assign a variable to each object (like obj_1), so that the code will be shorter? Each object should be accessible outside the loop

obj_1.do_sth()
1

8 Answers 8

81

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

In this case, why not make a list of objs?

objs = [MyClass() for i in range(10)]
for obj in objs:
    other_object.add(obj)

objs[0].do_sth()
Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to assign generic variable names? like "obj_%s" %s
Then use a dictionary instead of a list. Your data has some structure (e.g., you have keys relating to values, or just a list of values, etc) and the Python data structures you choose should reflect that.
20

you can use list to define it.

objs = list()
for i in range(10):
    objs.append(MyClass())

3 Comments

What if the number of classes is nuknown?
Since you're creating a list of objects you must know the number of objects your list must have, I guess you can always replace the number with a variable.
and if you're creating an object based on a conditions, you can use a while loop, where if the condition is true an object will be appended, to the list.
18

Creating a dictionary as it has mentioned, but in this case each key has the name of the object name that you want to create. Then the value is set as the class you want to instantiate, see for example:

class MyClass:
   def __init__(self, name):
       self.name = name
       self.checkme = 'awesome {}'.format(self.name)
...

instanceNames = ['red', 'green', 'blue']

# Here you use the dictionary
holder = {name: MyClass(name=name) for name in instanceNames}

Then you just call the holder key and you will have all the properties and methods of your class available for you.

holder['red'].checkme

output:

'awesome red'

Comments

6

Using a dictionary for unique names without a name list:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

Output:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."

Comments

2

I hope this is what you are looking for.

class Try:
    def do_somthing(self):
        print 'Hello'

if __name__ == '__main__':
    obj_list = []
    for obj in range(10):
        obj = Try()
        obj_list.append(obj)

    obj_list[0].do_somthing()

Output:

Hello

2 Comments

but I can't access the objects outside the loop that way
Yes i get your point. I have updated my example please see that. Here I have appended the objects in a list and then you can use the object outside the loop any were. Sorry but my solution is no different then others.
0

Hi there here is the answer I think they wanted below:

class Neuron:
  def __init__(self, name):
    self.name = name
  
    
Neurons=[]

for x in range(6):  
 Neurons.append(Neuron(x))  
  
for x in Neurons:
 print(x.name)

print(Neurons)

Comments

-1

This solution helps to create several instances of a class using a for loop as well as the globals() function.

class Cir:
    def __init__(self, name):
        self.name = name

This code defines a class called Cir with an __init__ method that takes a single argument name and assigns it to the object's name attribute.

for i in range(5):
    inst_name = "my_instance_" + str(i)
    globals()[inst_name] = Cir(inst_name)

This loop creates five instances of the Cir class and assigns them to global variables with names that depend on the value of the loop variable i. The variable inst_name is created as a string that adds the constant string my_instance_ with the string representation of the loop variable i. Then, the globals() function returns a dictionary of the global symbol table, and the resulting dictionary is accessed using inst_name as a key to add a new global variable with the name specified in inst_name and the value of the newly created instance of the Cir class with the name attribute set to inst_name.

print(my_instance_3.name)

This line of code prints the name attribute of the my_instance_3 and ensures that the instances were created properly.

Comments

-1

I did so, but the IDE indicates an error. You can experiment. eval() and exec() create vulnerable code sections.

class LinkedList:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


for i in range(1, 11):
    exec(f'linked_{i} = LinkedList({i})')
    if i > 1:
        exec(f'linked_{i - 1}.next = linked_{i}')


print(linked_1)  # <__main__.LinkedList object at 0x00000258AF6E3B80>

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.