I have a class that I'm trying to create objects for with a given variable adjusted by a loop. I'm struggling to explain so perhaps an example will help. The actual class is more complicated than the below, but the general idea is the same. The below method works, but feels very wrong.
#!/usr/bin/python
class Cuboid:
# default values for new instances
width = 123
height = 456
depth = 789
def __init__(self, var, val):
exec("self." + var + " = val") # This feels un-pythony
def area(self):
return self.width*self.height*self.depth
param_list=[
['width',[5,10,15,20]],
['height',[5,10,15,20]]
]
for param_i in range(0,len(param_list)):
for val_i in range(0,len(param_list[param_i][1])):
thisCuboid = Cuboid(param_list[param_i][0],param_list[param_i][1][val_i])
print(str(thisCuboid.area()))
This gives the expected output:
1798920
3597840
5396760
7195680
485235
970470
1455705
1940940
Apologies if the question is poorly worded, I'm quite new to python. Please feel free to suggest better wording/ask for clarification!
Note that the actual number of parameters that need changing is much more (something like a 20 dimensional cuboid to extend the analogy and the "area" depends on all 20 values), so the simple approach (create a list for each parameter and loop through the lists in turn, setting the named parameter accordingly) gets messy quickly (I need to add a loop for each of the parameters I want to change)