-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.

4
  • obj + i in the lhs won't work like you think. Commented May 26, 2018 at 13:39
  • why you are not using a list to store the objects instead of constructing their names? Commented May 26, 2018 at 13:40
  • Can you please elaborate Commented May 26, 2018 at 13:40
  • have a look here: stackoverflow.com/a/3182241/986160 (possible duplicate) Commented May 26, 2018 at 13:42

3 Answers 3

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>]
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.