0

On integers in python we can use:

>>> a = 1
>>> a += 2
>>> print(a)
3

But if you look in available methods in the integer object you will not find the related method __iadd__. E.g. you get an exception if you execute:

a.__iadd__(2)  # equal to a += 2

So how is the operator += working on integers? And is there a way to reach a builtin method to do the operation so that we can use it in a list comprehension like this:

>>> a = 0
>>> summands = [1, 4, 5, 7, 9]
>>> [a.__iadd__(a,i) for i in summands]
>>> print(a)
3

The problem is that we can use just method calls and not the = operator in this case.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
B.R.
  • 234
  • 2
  • 7
  • 2
    If there's no `__iadd__` then the interpreter uses `__add__` and a regular assignment. I'm not sure what your goal is with that list comprehension, but it looks funny. – timgeb Oct 27 '21 at 07:34
  • If you look at `int` class you see it inherits from `object`. `class int(object)` So you might take need to take a look to that class? – MSH Oct 27 '21 at 07:36
  • What do you want to achieve with that comprehension?! There are certainly "normal" ways to do whatever you want to do there, perhaps `sum` or `reduce`… – deceze Oct 27 '21 at 07:39
  • 2
    if there is no `__iadd__` method for a type (like `int`), python will use `a = a + i`. as `int`s are immutable, there must be no way to change them in-place. – hiro protagonist Oct 27 '21 at 07:39
  • https://docs.python.org/3/library/operator.html#in-place-operators – jonrsharpe Oct 27 '21 at 07:43
  • The hint regarding integers are immutable makes the things clear for me. Thanks. I don't understand why the question is a duplicate. In the other question my question is not answered (or I do not see it). – B.R. Oct 27 '21 at 08:54

0 Answers0