I have a class which calculates a moving average which could probably be improved. The size of the averaging window must be flexible.
It currently works by setting the size of the window then sending it updates thus:
twoday = MovingAverage(2) # twoday.value is None
twoday = twoday.update(10) # twoday.value is None
twoday = twoday.update(20) # twoday.value == 15
twoday = twoday.update(30) # twoday.value == 25
I thought it would be cool if it worked something more like this:
twoday = MovingAverage(2) # twoday is None
twoday += 10 # twoday is None
twoday += 20 # twoday == 15
twoday += 30 # twoday == 25
Is this stupid?
Is it possible?
You can emulate numeric types by adding methods such as
__add__(), which exactly do what you want.Just add methods such as
to what you currently have.
If you want to come close to what a float does, you could add methods such as
(the latter gives you a way to do
somevalue + twodayand get the expected value)and
__mul__/__rmul__, the same with div, and so on. Your only special case is probably the__iadd__()mentionned above.