I would like to understand why the following three, extremely simple, python codes give (apparently) inconsistent answers. It's just a toy exercise to understand what's happening, not a real-world problem. The class myList(list) inherits from list and defines a method "add" that should mimic the well-known "extend" method. I've tried to do this in three ways, with the direct use of extend, with the + operator and with +=. However, with great surprise, I get inconsistent answers. Notice that, among the three codes, a single line (inside the add method) changes.
CODE 1: self.extend(item)
class myList(list):
def add(self,item):
self.extend(item)
l = myList([1,2])
l.add([3,4])
print(l)
Prints [1, 2, 3, 4]
CODE 2: self = self + item
class myList(list):
def add(self,item):
self = self + item
l = myList([1,2])
l.add([3,4])
print(l)
Prints [1, 2]
CODE 3: self += item
class myList(list):
def add(self,item):
self += item
l = myList([1,2])
l.add([3,4])
print(l)
Prints [1, 2, 3, 4]
I am a bit confused... what's happening?
Thank you in advance.
self = self + item
does not modify the object, only the local variable inside the method.
By using +
the interpreter is calling __add__
in list
, which creates a new list, and you're then making the self
variable point to it within the add
method, and when the method exits its value is discarded.
On the other hand, the +=
version calls the __iadd__
method of the list
class, which updates its contents as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With