Reputation: 717
I know how to create multiple objects of the same class using a loop, similar to this How to create multiple class objects with a loop in python? However, what I want is different because each object has to be initialised with different arguments my program now reads all the information (the arguments) from a file and store them in a python dictionary, like this:
objects={'obj1':['object1','Tom',10],'obj2':['object2','John',13]}
and because the number of the objects which are needed depend on the information found on the file .. I want to know if there's a way to automatically create (maybe by using a loop !) multiple class objects and initialised them with their different arguments .. Instead of declare them as follows:
obj1 = MyClass('object1','Tom',10)
obj2 = MyClass('object2','John',13)
.
.
.
etc
Upvotes: 2
Views: 3555
Reputation: 44092
>>> objects={'obj1':['object1','Tom',10],'obj2':['object2','John',13]}
>>> instances = []
>>> for name, args in objects.items():
inst = MyClass(*args)
instances.append(inst)
Or directly:
>>> [MyClass(*args) for name, args in objects.items()]
[<MyClass: object1, Tom, 10>, <MyClass: object2, John, 13>]
or even simpler, ignoring names:
>>> [MyClass(*args) for args in objects.values()]
[<MyClass: object1, Tom, 10>, <MyClass: object2, John, 13>]
or returning a dictionary (works in Python 2.7+)
>>> {name: MyClass(*args) for name, args in objects.items()}
{'obj1': <MyClass: object1, Tom, 10>, 'obj2': <MyClass: object2, John, 13>}
This would even work if you have dynamic number of arguments for creating your instances (assuming your class constructor can handle this variable number - using defaults)
Using itertools.starmap
>>> from itertools import starmap
>>> list(starmap(MyClass, objects.values())
[<MyClass: object1, Tom, 10>, <MyClass: object2, John, 13>]
Upvotes: 4
Reputation: 35109
objects={'obj1':['object1','Tom',10],'obj2':['object2','John',13]}
class MyClass():
def __init__(self, var1, var2, var3, *args):
self.var1 = var1
self.var2 = var2
self.var3 = var3
for i in objects.keys():
my_class = MyClass(*objects[i])
print my_class.__dict__
{'var1': 'object1', 'var3': 10, 'var2': 'Tom'}
{'var1': 'object2', 'var3': 13, 'var2': 'John'}
Upvotes: 2
Reputation: 4129
One thing you could do is create a list containing all of your new MyClass
objects, like so:
class_objects = []
for o in objects.values():
class_objects.append(MyClass(o[0], o[1], o[2]))
This makes a list called class_objects
that contains all of your MyClass
objects from the file.
Upvotes: 1