In-place methods in subclasses

55 views Asked by At

I am trying to subclass list in order to create an in-place method that updates self with the item-wise sum of itself and a new list. Example:

This is how I tried to do it:

class RecordBook(list):
    def accumulate(self, new_values):
        self = RecordBook([x+y for x, y in zip(self, new_values)])

With the though being that rebinding back to self will modify it in-place. It does not work however.

>> d = RecordBook([1, 2, 3, 4, 5, 6])
>> d
[1, 2, 3, 4, 5, 6]
>> d.accumulate([1]*6)
>> d
[1, 2, 3, 4, 5, 6]  # should have been [2, 3, 4, 5, 6, 7]

Why is that failing the task and how would one go about this?

1

There are 1 answers

0
Reblochon Masque On

Here is one approach subclassing collections.UserList, and modifying the underlying self.data of the subclass.

As explained by @Deceze in the comments:

self is just a local variable, and assigning something else to it doesn't replace the existing object

UserList exposes the self.data attribute that can be modified "in-place"

from collections import UserList


class Accumulator(UserList):
    def accumulate(self, seq):
        for idx, elt in enumerate(seq):
            self.data[idx] += elt


if __name__ == '__main__':
    d = Accumulator([1, 2, 3, 4, 5, 6])
    d.accumulate([1]*6)
    print(d)

output:

[2, 3, 4, 5, 6, 7]