Problem with __sub__

David Raymond David.Raymond at tomtom.com
Thu Mar 23 14:07:25 EDT 2023


I believe your problem is __rsub__, not __sub__.
When you have <something else> <operator> <something of this class> then that uses the "r" version of the operators.

In your __rsub__ (used when you have <other> - <this>) you instead return <this> - <other> which is backwards.

Notice how the final return should also be -4,95 and not the +4,95 it's returning.

> If on the left side is '0' the result of a subtraction is wrong.
> 
> *    b1 = Betragswert(500)
>      b2 = 0 + b1
>      b3 = 0 - b1
>      b4 = 5 + b1
>      b5 = 5 - b1*
> 
> print(b1, b2, b3, b4, b5) shows 5,00 5,00 5,00 5,05 4,95; the third
> value (b3) should be -5,00 (not 5,00).
> 
> Why is the substraction wrong?
>      def __rsub__(self, zweiter):
>          if not isinstance(zweiter, type(self)):
>              zweiter = Betragswert(zweiter)
>          return Betragswert(self._Betrag - zweiter._Betrag)


More information about the Python-list mailing list