Given the following class:
class Example():
def __init__(self, numerator1, denominator1, numerator2, denominator2):
self.numerator1 = numerator1
self.denominator1 = denominator1
self.numerator2 = numerator2
self.denominator2 = denominator2
I've created a couple of objects:
objects = [Example(1, 2, 2, 1), Example(1, 2, 2, 1)]
Now I want to perform the same operation to each of the two pairs of numerator/denominator combinations:
sum(m.numerator for m in objects) / sum(m.denominator for m in objects)
To try and stay in keeping with DRY I'd like to create a single function to perform this operation and simply change the numerator and denominator combinations each time. Something like:
def standard_func(numerator, denominator, objects):
return (sum(m.numerator for m in objects) / sum(m.denominator for m in objects)
comb1 = standard_func(<numerator1>, <denominator1>, objects)
comb2 = standard_func(<numerator2>, <denominator2>, objects)
I can't figure out how to get the above example to work as the sum
function needs to know that the numerator or denominator is associated with an Example
instance.
I've experimented with incrementing class variables however I have a for loop that generates multiple iterations of the objects
list and I want a unique sum of num/denom per list. I suppose I could reset the class variable total on each loop - maybe this is one solution?