John Mee
John Mee

Reputation: 52243

Can I make a class which behaves like an immutable (float)?

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?

Upvotes: 2

Views: 102

Answers (1)

glglgl
glglgl

Reputation: 91017

You can emulate numeric types by adding methods such as __add__(), which exactly do what you want.

Just add methods such as

def __iadd__(self, other):
    self.update(other)
    return self

def __add__(self, other):
    return self.value + other

def __str__(self):
    return str(self.value)

to what you currently have.

If you want to come close to what a float does, you could add methods such as

def __float__(self):
    return self.value

def __radd__(self, other):
    return other + self.value

(the latter gives you a way to do somevalue + twoday and get the expected value)

and __mul__/__rmul__, the same with div, and so on. Your only special case is probably the __iadd__() mentionned above.

Upvotes: 6

Related Questions