Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I change the base class value in a python subclass?
    primarykey
    data
    text
    <p>When subclassing a base type, like float, is it possible to "recalculate" or "reassign" the original value? If I have the following class definition,</p> <pre><code>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) </code></pre> <p>When I start with</p> <pre><code>&gt;&gt;&gt; ma = MovingAverage(10, 3) &gt;&gt;&gt; ma 10.0 </code></pre> <p>but</p> <pre><code>&gt;&gt;&gt; ma.add(3) 6.5 &gt;&gt;&gt; ma 10.0 </code></pre> <p>The other class definition I've tried is this:</p> <pre><code>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) </code></pre> <p>This time, when I start with</p> <pre><code>&gt;&gt;&gt; ma = MovingAverage([10], 3) &gt;&gt;&gt; ma 10.0 </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt; ma.add(3) 6.5 &gt;&gt;&gt; ma 10.0 &gt;&gt;&gt; ma = ma.add(3) &gt;&gt;&gt; ma 5.333333333333333 </code></pre> <p>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 <code>ma</code> is the value that I'm looking for? Or do I need to define a <code>value</code> attribute, change the base class to <code>object</code>, and abandon my pretense that I have a chance of controlling the return value of the class?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload