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.