0

I want to write a function that creates multiple instances of a class but I'm having some problems. What I want to do is something like this:

class MyClass:
    def __init__(self):
        self.x = 0
        self.y = 1



for i in range(10):
    exec ("obj{} = MyClass()".format(i))

With a loop I can create my multiple instance of the class so when I call in the Python Shell obj1 as example it returns something like:

>>> obj1
<__main__.MyClass object at 0x0036F0F0>
>>> obj2
<__main__.MyClass object at 0x0036F0D0>

What that means is that the obj0, obj1, obj2 was created succesful, that's awesome but I want to reply the same process but with a function that can receive (n) numbers of loop repeats.

class MyClass:
    def __init__(self):
        self.x = 0
        self.y = 1    

def function_create_multiple_instances(n):
    for i in range(n):
        exec ("obj{} = MyClass()".format(i))
        print(i)

function_create_multiple_instances(10)

When I try the Python Shell, I have this that means that the objects was not created

>>> obj1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'obj1' is not defined
>>> obj2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'obj2' is not defined
>>>

So I don't know whats that happening, so if anyone can help me I will really appreciate that.

DarkSuniuM
  • 2,523
  • 2
  • 26
  • 43
nische
  • 1
  • 1
  • 2
  • use `rr=[]` (an empty list) then replace `exec ("obj{} = MyClass()".format(i))` with `rr.append(MyClass())` then you can reference your classes as items in a list rr[0], rr[1], etc – Mohammad Athar Nov 05 '18 at 19:31

1 Answers1

1

Creating variables in a some function will bind those variables to the scope of the function, and they can't be accessed outside that function. To declare global variables inside function, you have to explicitly mention them as global. Like global obj1.

So, your function will be changed to:

def function_create_multiple_instances(n):
    for i in range(n):
        exec("global obj{0}\nobj{0} = MyClass()".format(i))
        print(i)

Now, calling this function as function_create_multiple_instances(10) will create the global objects, which you'll be able to access through shell.

Ahmad Khan
  • 2,655
  • 19
  • 25