0

I have implemented a class TimeWindow, which overloads __add__, __sub__ and __contains__.

These operations handle instances of TimeWindow, int, float and return instances of TimeWindow when appropriate.

Now, I understand that the +, - and in operators when encountering foo + other will invoke the proper functions when foo is an instance of TimeWindow and will fail when int or float are the first argument as the operation is unsupported by an int or float type.

My current solution is:

  1. Convert int and float types to equivalent TimeWindow type before the operation.
  2. Ensure the first argument is TimeWindow type when possible.

I know of solutions such as this in other languages. Is there an equivalent solution to this in python?

martineau
  • 119,623
  • 25
  • 170
  • 301
MYousefi
  • 978
  • 1
  • 5
  • 10
  • Do you know about [reflected operators](https://docs.python.org/3/reference/datamodel.html#object.__radd__)? If `a.__add__(b)` returns `NotImplemented`, Python will attempt to call `b.__radd(a)__`. Likewise for other binary operator methods. – Brian61354270 Jan 24 '22 at 00:26
  • @Brian: Gee, and I always thought that `r` prefix stood for "reversed". ;¬) – martineau Jan 24 '22 at 01:41

0 Answers0