-3

I am new to python recently I am working on a project in I created a class:-

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

I want to create 50 objects of this class which sholud be named as obj1, obj2, obj3,..., obj50 I am trying to create these classes like

for i in range(1,51):
    obj + i = foo(i)

So that 50 objects like obj1, obj2, obj3,..., obj50 are created with names as 1, 2, 3,...,50. But for some reason this is not working for me. Can anyone tell what am I doing wrong here. I know that I can use a list to store the objects but for some reason I would like to do it this way. Any help is highly aprreciated.

3 Answers3

2

You can do this like so:

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

    def __str__(self):
        return name

    def __repr__(self):  # will print the "name" as repres of this obj
        return self.name

objects= [foo(str(i)) for i in range(1,51)] # create 50 foo-objects named 1 to 50

print(objects) # list that contains your 50 objects

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 
 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 
 46, 47, 48, 49, 50]

If you remove the def __repr__() you get smth like:

[<__main__.foo object at 0x7fd4e9b78400>, 
 <__main__.foo object at 0x7fd4e9b78470>, 
 ... etc ..., 
 <__main__.foo object at 0x7fd4e9afd940>, 
<__main__.foo object at 0x7fd4e9afd9b0>]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

I think you might need to learn the concept of Array if you haven't already known.

obj = [] # create an empty array
for i in range(1,51):
    obj.append(foo(i))

and instead of try using obj1, obj2, ... you can access it using obj[1], obj[2], .... This is basically an array.

digitake
  • 846
  • 7
  • 16
0

You can programatically set the attribute to the current module which is what you are trying to do. Creating a list of objects is much better.

import sys

thismodule = sys.modules[__name__]   

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

for i in range(1,51):
    setattr(thismodule, 'obj' + str(i), foo(i))
Nishant
  • 20,354
  • 18
  • 69
  • 101