Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+= operator in python for __setitem__ (addition in place for square brackets)

To define a class behaviour in the following statement:

my_object[item] = ...

I know I need to define the __setitem__ method.

What method do I need to define for the following statement:

my_object[item] += ...
like image 260
DevShark Avatar asked Sep 06 '25 20:09

DevShark


1 Answers

my_object needs __getitem__ to retrieve the initial value of my_object[item] and __setitem__ to set the new value.

Additionally, Python needs a way to perform the addition. Either my_object[item] needs to implement the addition with __add__ or __iadd__, or the object on the right side of the += needs to implement __radd__.

like image 142
user2357112 supports Monica Avatar answered Sep 11 '25 07:09

user2357112 supports Monica