3

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] += ...
DevShark
  • 8,558
  • 9
  • 32
  • 56
  • You are looking for `__iadd__` I believe. – idjaw Mar 25 '16 at 21:45
  • The question was answered [before](http://stackoverflow.com/questions/1047021/overriding-in-python-iadd-method) – Hang Mar 25 '16 at 21:45
  • 1
    There is no such thing as `__isetitem__`. For `my_object[...]`, you can define `__setitem__` and `__getitem__`, but to make `my_object[item] += ...` different from `my_object[item] = my_object[item] + ...`, you would need to modify the class that `my_object[item]` is an instance of. – zondo Mar 25 '16 at 21:50
  • @Hang: no, that answer does not address this question. The accepted answer is correct. The point is that __iadd__ is not what is needed for this situation, but a correct implementation of __getitem__ besides __setitem__ is. That is not obvious. – wessel Dec 12 '17 at 14:38

2 Answers2

4

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__.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

__setitem__ will cover you with regard to your container class; it's called when you do any augmented assignment just as with regular assignment. As far as your class can tell, there's no difference between x[i] += 1 and x[i] = x[i] + 1.

If you need to treat += differently from = or from -=, that's handled by the special methods of the item's class.

kindall
  • 178,883
  • 35
  • 278
  • 309