0

I made a custom mathematical object (Fractions) that can use some operators (for ex. '+' thanks to__add__())

This means my Fraction can work with ints:

Fraction(1/2) + 0.5 == 1 # True

I would like ints and floats to work with my object as well. for example:

0.5 + Fraction(1/2) == 1 # Error, not supported...

How do I make my object work with built-in objects?

MBee
  • 78
  • 7
  • 3
    Implement `__radd__` – DeepSpace Mar 07 '21 at 17:59
  • See for example https://stackoverflow.com/questions/51298551/python-operator-overloading-radd-and-add – Thierry Lathuille Mar 07 '21 at 18:00
  • 1
    Btw there is already a [fractions](https://docs.python.org/3/library/fractions.html) module that supports commutative addition. – HTF Mar 07 '21 at 18:04
  • 2
    Side-note: `Fraction(1/2)` is passing `0.5` to the `Fraction` constructor. You can't actually implement sane fractions that accept a `float` as their constructor due to precision loss. You almost certainly want `Fraction(1, 2)`. – ShadowRanger Mar 07 '21 at 18:09
  • Thanks @DeepSpace. Good to know @HTF, but I'm doing it for fun anyway lol. @ShadowRanger I'm aware. floats are optional and not recommended in my case(I can pass`Fraction(1, 2)`), they are there just for comfort. – MBee Mar 07 '21 at 18:16

0 Answers0