chase
chase

Reputation: 3782

Best way to set sum over other objects properties

I need to set a property of one object to the sum of another objects properties and have it readjust whenever a modification is made to those objects. Is the following the best way to do this?

# object A has several object B's - (object A aggregates object B)
class objectA:
    def __init__(self, somevar):
        self.somevar = somevar

        self.list_of_Bs = [B(var) for b in range(0,2)]

        # sum of several functions or something
        self.summed_array = sum(b.array for b in self.list_of_Bs)

class objectB:
    def __init__(self, var):
        self.var = var

        self.array = gaussian_function(x, center, var, etc)

Upvotes: 0

Views: 95

Answers (1)

mgilson
mgilson

Reputation: 310019

I think that the most bullet-proof way is to make self.summed_array a property:

class objectA(object):
    def __init__(self,somevar):
        ...

    @property
    def summed_array(self):
        return sum(b.array for b in self.list_of_Bs)

Of course, if this summing is going to be expensive, you may want to make this a method, rather than a property to make it explicit to the user that computations are being performed. Then the user can choose whether to cache the value in some other way if they need to.

Your other option is to modify self.list_of_Bs so that it knows when the list is modified and so that it holds a reference on the instance of objectA that it is bound to. That's going to be a lot more work...

Upvotes: 3

Related Questions