In Python, when I run the operation: 1 / 0, its default behavior is generating an exception: "ZeroDivisionError: float division by zero"
How to overload this default behavior so that I can get: 1 / 0 => math.inf
CodePudding user response:
You need to define your own class and within that define methods __truediv__
(/
) and __floordiv__
(//
) at a minimum. If you only define those two
for example would not work (see error below).
import math
class MyFloat:
def __init__(self, val):
self.val = val
def __truediv__(self, other):
if other.val == 0:
return math.inf
return self.val / other.val
def __floordiv__(self, other):
if other.val == 0:
return math.inf
return self.val // other.val
one = MyFloat(1)
zero = MyFloat(0)
print(one / zero)
print(one // zero)
// will throw an error (PyCharm will also pick up on this)
print(one zero)
Expected output
Traceback (most recent call last):
File "/home/tom/Dev/Studium/test/main.py", line 24, in <module>
print(one zero)
TypeError: unsupported operand type(s) for : 'MyFloat' and 'MyFloat'
inf
inf
For a list of those special Python function see this website.
CodePudding user response:
you might have to write your own library that allows this to happen, it might not be too hard to make something simple that sees when you get that error and instead assigns that number to 'infinity'