How does the sum assignment operator work internally?

Asked

Viewed 45 times

-1

I am creating a class and I want its objects to be summed up, using the sum operator or the sum assignment operator. I know that to use the sum operator, we must create for the class the special method __add__, as in the code below:

class list(object):
    def __add__(self, value, /):
        # Implementação de list

[1, 2, 3] + [4, 5, 6] # Utilizando o operador de soma, o retorno será: [1, 2, 3, 4, 5, 6]

But for the operator of sum assignment? Do you use this same method? I’m asking this question because I can’t understand how this operator works internally.

I even thought about the possibility of the method __add__ return the modified object itself, but it seems that this is not what happens. If we create, for example, a list and use that operator to add it with another one, the result will be the same list.

lista = [1, 2, 3]
id(lista) # 39196952
lista += [4, 5, 6]
id(lista) # 39196952  <- É a mesma lista. Houve uma modificação diretamente no objeto.

But if we use only the sum operator, the result is a new list (a new object):

lista = [1, 2, 3]
id(lista)      # 39196952
lista_nova = lista + [4, 5, 6]
id(lista_nova) # 39241608  <- What!? Ele retornou um novo objeto com a soma realizada.

Clearly there is a difference in the way in which the two operators work internally. That said, I would like to know:

  • How the sum assignment operator works internally?
  • The method __add__ has connection with that operator? If not, which method to use?
  • If I understand correctly, everything you want to know already has here: in the case of +=, is called the method __iadd__, and if it doesn’t exist, it’s used __add__

  • @hkotsubo Ah, thanks. I had not found that. I removed the question or vote to close it as duplicate?

1 answer

-1

Operators + and += have different implementations when you use += (__iadd__) on an object of the type list the original list is mutated, so the memory reference remains. Already the operator + (__add__) generates a new object of type list and returns it.

You can read more about it in this question here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.