Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List inheritance: "extend" vs "+" vs "+=" [duplicate]

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.

like image 854
F.B. Avatar asked Nov 20 '19 10:11

F.B.


1 Answers

    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.

like image 190
Tordek Avatar answered Oct 25 '22 01:10

Tordek