I’m trying to define a new type of division such that 1/0 doesn’t raise a ZeroDivisionError, instead, it returns a new object called infty(0)
, which is defined as follow:
<code>class infty:
def __init__(self, sign:int):
if sign > 0:
self.sign = 1
elif sign < 0:
self.sign = -1
else:
self.sign = 0
def __repr__(self):
if self.sign > 0:
return '∞'
if self.sign < 0:
return '-∞'
return '?'
</code>
<code>class infty:
def __init__(self, sign:int):
if sign > 0:
self.sign = 1
elif sign < 0:
self.sign = -1
else:
self.sign = 0
def __repr__(self):
if self.sign > 0:
return '∞'
if self.sign < 0:
return '-∞'
return '?'
</code>
class infty:
def __init__(self, sign:int):
if sign > 0:
self.sign = 1
elif sign < 0:
self.sign = -1
else:
self.sign = 0
def __repr__(self):
if self.sign > 0:
return '∞'
if self.sign < 0:
return '-∞'
return '?'
so I have made a new function:
<code>def safediv(a:int, b:int) -> float|infty:
if b == 0:
return infty(0)
return a/b
</code>
<code>def safediv(a:int, b:int) -> float|infty:
if b == 0:
return infty(0)
return a/b
</code>
def safediv(a:int, b:int) -> float|infty:
if b == 0:
return infty(0)
return a/b
and tried to assign it to truediv by int.__truediv__ = safediv
but it fails with the error message:
<code> int.__truediv__ = safediv
^^^^^^^^^^^^^^^
TypeError: cannot set '__truediv__' attribute of immutable type 'int'
</code>
<code> int.__truediv__ = safediv
^^^^^^^^^^^^^^^
TypeError: cannot set '__truediv__' attribute of immutable type 'int'
</code>
int.__truediv__ = safediv
^^^^^^^^^^^^^^^
TypeError: cannot set '__truediv__' attribute of immutable type 'int'
Is there a way to achieve the effect that 1/0
returns infty(0)
?
New contributor
Mr. W is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5