Reputation: 141
I want to write a program that runs multiple classes. My code looks like
list_of_classes = [class1, class2, class3]
def run_class(class_):
print("Running class ", class_.__name__) #All my classes have such attribute
x = class_()
x.doStuff()
#etc
for class_ in list_of_classes:
run_class(class_)
Problem is, that for some classes, I want to pass some arguments (which are optional). For example, let's assume that for class1 I want to pass the argument iterations = 150
.
How do I do that? My first thought is to change the list_of_classes
like so:
list_of_classes = [(class1, 'iterations=150'), (class2, ''), (class3, '')]
But how do I pass the second part of the tuple as argument?
I do not want to place the arguments directly in the list like so:
list_of_classes = [class1(iterations=150),class2,class3]
because I will not be able to use the __name__
attribute in my function.
Upvotes: 0
Views: 24
Reputation: 434
You can try:
list_of_classes = [
(class1, [], {'iterations': 150}),
(class2, [], {}),
(class3, [], {}),
]
for class_, args, kwargs in list_of_classes:
run_class(class_, *args, **kwargs)
Upvotes: 1