Strange behavior when inheriting from a list in python

I have been doing inheritance recently, and I am a little confused by the behavior of the following:

class Foo(list):

    def method(self, thing):
        new = self + [thing]
        print(new)
        self = new
        print(self)

    def method2(self, thing):
        self += [thing]

>>> f = Foo([1, 2, 3, 4, 5])
>>> f.method(10)
[1, 2, 3, 4, 5, 10]
[1, 2, 3, 4, 5, 10]
>>> f
[1, 2, 3, 4, 5]
>>> f.method2(10)
>>> f
[1, 2, 3, 4, 5, 10]

Why method2does the in-place method work, but the first does not work?

+1
source share
2 answers

Since the operators work on the spot.

self = self + [thing]creates a new list and places it in a local variable self, overriding the passed one. But it does not modify the object itself. Inside he performs self = self.__add__([thing]).

self += [thing], OTOH, changes the list in place. Inside, he first tries self = self.__iadd__([thing]). iaddmeans add place. Only if this does not exist is called self = self.__add__([thing]).

, __add__() . __iadd__(), , , . , , .. . self , . , , .

+2

list.__add__() ( +) , list.__iadd__() ( +=) .

0

All Articles