1

Simplified sample code:

    class Numbers(object):

    def __init__(self, value):
    self.value = value


instance1 = Numbers(100)
instance2 = Numbers(120)
instance3 = Numbers(76)

I would like to set a variable within the class (or otherwise) that would be set to the total sum of all the values (100 + 120 + 76 in this case). Is it possible to do with a class variable?

user2390206
  • 123
  • 1
  • 9
  • I already saw this: http://stackoverflow.com/questions/10879867/sum-average-an-attribute-of-a-list-of-objects-in-python but did not manage to use the information in that thread to solve my problem. – user2390206 Oct 19 '16 at 19:24

1 Answers1

2

If you want the sum to be of all instances ever created since your program started, and you don't expect an instance's value to ever change after it's created, it is easy to update a sum class variable in the __init__ method:

class Numbers(object):
    sum = 0

    def __init__(self, value):
        self.value = value
        Numbers.sum += value

If you want the sum to only include the currently "live" instances, or if you want the sum to accurately reflect changes in instance's value over time, it's going to be rather more complicated. To deal with deleted instance, you could add a __del__ method. And you could do the updating of the sum in the setter of a property for value, with logic to subtract the previous value when there's a change.

def Numbers(object):
    sum = 0

    def __init__(self, value):
        self._value = 0      # initialize this value so the property's setter works
        self.value = value

    def __del__(self):
        Numbers.sum -= self._value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        Numbers.sum += value - self._value
        self._value = value

This implementation can still have issues though, since the __del__ method may be called later than you expect it to be (Python's garbage collection is never guaranteed).

Blckknght
  • 100,903
  • 11
  • 120
  • 169