We are struggling with the following problem in python 3: we have defined a class, which inherits from list. We want to incorporate a method by which it can update itself to a new instance of this class.
Some very simple code to illustrate what we mean:
class test(list):
def update(self):
self = test(['a','b','c','d'])
x = test([1,2,3])
x.update()
print(x)
This code returns the original list [1,2,3], which shows that the object x indeed hasn't been updated. Is there a way to let an object update itself completely? We need this to work for lists of different lengths.
selfis just another variable. Method objects cause the current instance to be assigned to that name (just like other values are assigned to other function parameters), but like other names, assigning to them will only change what object the name refers to. Other names that reference the same object, likex, do not change along.That's because names in Python code are just like tags, and
self = <something else>is like taking the tag of the old instance and putting it on another object. Any other tags still attached to the old object are not moved! Becausexstill references the old instance, it is not going to see that you put theselftag on another object.Either your
update()method needs to return the new object (so that the caller can update their reference to point to the new object), or change the list in-place (at which point all references to the object will see the same change.Returning the object means the caller is responsible for doing something with the return value:
Or you can assign to indices of the list itself; this changes what the contents of the list point to. You can use
selfjust like any other reference, sox[0] = 5would change index 0, so wouldself[0] = 5. And if you assign to a slice you can change multiple indices at once. The identity slice,[:], lets you change all indices at once, and you can assign more or fewer values to grow or shrink a list. Assigning toself[:]changes all indices, and lets you change all indices to point to any number of different values.So:
The above replaces all indices with the values in the other list. All references to the instance will see the change; both as
selfandx, and any other such references.Demo of what this means: