-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
@hkotsubo Ah, thanks. I had not found that. I removed the question or vote to close it as duplicate?
– JeanExtreme002