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?
Here is one approach subclassing
collections.UserList
, and modifying the underlyingself.data
of the subclass.As explained by @Deceze in the comments:
UserList
exposes theself.data
attribute that can be modified "in-place"output: