When subclassing a base type, like float, is it possible to "recalculate" or "reassign" the original value? If I have the following class definiti开发者_JS百科on,
import collections
class MovingAverage(float):
def __new__(self, initial_value, window):
self.d = collections.deque([initial_value], window)
return float.__new__(self, initial_value)
def add(self, new_value):
self.d.append(new_value)
print sum(self.d) / len(self.d)
# here, I want to _set_ the value of MovingAverage to
# sum(self.d) / len(self.d)
When I start with
>>> ma = MovingAverage(10, 3)
>>> ma
10.0
but
>>> ma.add(3)
6.5
>>> ma
10.0
The other class definition I've tried is this:
import collections
class MovingAverage(float):
def __new__(self, iterable, window):
self.d = collections.deque(iterable, window)
initial_value = sum(iterable) / len(iterable)
return float.__new__(self, initial_value)
def add(self, new_value):
self.d.append(new_value)
return MovingAverage(self.d, self.d.maxlen)
This time, when I start with
>>> ma = MovingAverage([10], 3)
>>> ma
10.0
and
>>> ma.add(3)
6.5
>>> ma
10.0
>>> ma = ma.add(3)
>>> ma
5.333333333333333
However, I think (I haven't tested to find out) it makes this significantly slower. So, can it be done? Can I somehow set it so that the return from ma
is the value that I'm looking for? Or do I need to define a value
attribute, change the base class to object
, and abandon my pretense that I have a chance of controlling the return value of the class?
No. Since these types are immutable, you should be using encapsulation, not inheritance.
I don't think that Ignacios answer above needs any improvements, but since I had this class laying around I just thought I should share. It avoids doing big sum operations many times and also avoids rounding errors that might occur if you use a (more) naïve algorithm:
class MovingAverage:
def __init__(self):
self.sum = None
self.num = 0
def add(self, val):
if self.sum is None:
self.sum = val
else:
self.sum += val
self.num += 1
return self.val
@property
def val(self):
if self.sum is None:
return None
else:
return self.sum/self.num
if __name__ == "__main__":
print("Running small test suite")
fail = False
m = MovingAverage()
try:
assert m.val is None, "A new MovingAverage should be None"
assert m.add(10) == 10, "New average should be returned"
assert m.val == 10, "The average should update for each add"
assert m.add(20) == 15, "New average should be returned"
assert m.val == 15, "The average should update for each add"
assert m.add(0) == 10, "Adding zero should work"
assert m.add(-10) == 5, "Adding a negative number should work"
assert m.add(-1) == 19/5, "Result should be able to be a fraction"
except AssertionError as e:
print("Fail: %s" % e.args[0])
fail = True
if not fail: print("Pass")
精彩评论