0

I am creating a physics engine that needs a way to simulate immoveable objects, such as an object with infinite mass. I could use math.inf for this, and I have been, but then I would like some special features of it: inf / inf = 1, inf * 0 = 0, inf + -inf = 0 and inf - inf = 0. I thought of creating my own "Infinity" class, but then it would be very long for just a simple thing.

I then wondered if I could override some of the dunderscore methods (or "magic methods"), so that I could use the four equations above. I could just use isinf to check if they are infinity, but then it would be quite annoying to use. Is it possible to inherit from float or something to create my own infinity class?

EDIT: I know how to subclass from float, so now what do I need to override to completely use the equations?

Ray
  • 311
  • 1
  • 3
  • 14
  • I think this might help: https://stackoverflow.com/questions/5604713/creating-my-own-integer-object-in-python – Shashank Sep 02 '20 at 11:16
  • I've tried that, but it seems too cubersome to use when all that's different are 3 methods: `__mult__`, `__div__` and `__sub__`. Everything else is the exact same as `float`. How can I override the methods above? – Ray Sep 02 '20 at 11:28
  • Might be related how to subclass float: [Python: Can a subclass of float take extra arguments in its constructor?](https://stackoverflow.com/questions/35943789/python-can-a-subclass-of-float-take-extra-arguments-in-its-constructor) – Maurice Meyer Sep 02 '20 at 11:36
  • Also, I've seen other methods like `__radd__` or `__iadd__`. What do they do? – Ray Sep 02 '20 at 11:48
  • How do I undo the "this question already has answers here:"? – Ray Sep 02 '20 at 11:51

0 Answers0