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).