I see that metulburr already posted the simple answer while I was composing my reply but I have reputation (especially at work) of complicated answers, so I'll still post my answer.
Numeric types support a __neg__ method that returns a number with sign changed. Numeric methods also support a __pos__ method which (usually) returns the number unchanged. When multiple + or - symbols are present between two objects, the first symbol becomes addition or subtraction. The remaining symbols are applied directly to the right hand object by calling __neg__ or __pos__ as appropriate.
The += operator calls the __iadd__ method. Glossing over a few details, your intended code would be equivalent to:
- Code: Select all
ct.__iadd__(1)
The code you actually entered is parsed as:
- Code: Select all
ct.__add__((1).__pos__())
An addition is done but the result is never saved.
Can the + operator ever return a different number? Surprisingly, yes. For numeric types that have parameters that can be specified (say the precision of Decimal numbers), the + operator returns a number that is guaranteed to fit into the current precision. For example, if you have a value calculated to 50 digits of precision, and then you change the current precision to 40 digits, the + operator will return a number with 40 digits of precision.
- Code: Select all
>>> import decimal
>>> ctx=decimal.getcontext()
>>> ctx.prec=50
>>> decimal.setcontext(ctx)
>>> a=decimal.Decimal(1)/7
>>> a
Decimal('0.14285714285714285714285714285714285714285714285714')
>>> +a
Decimal('0.14285714285714285714285714285714285714285714285714')
>>> ctx.prec=40
>>> decimal.setcontext(ctx)
>>> a
Decimal('0.14285714285714285714285714285714285714285714285714')
>>> +a
Decimal('0.1428571428571428571428571428571428571429')
>>>