在 Python 中,當我運行操作:1 / 0 時,它的默認行為是生成例外:“ZeroDivisionError: float 除以零”
如何多載此默認行為以便我可以獲得:1 / 0 => math.inf
uj5u.com熱心網友回復:
您需要定義自己的類,并在該類中至少定義方法__truediv__( /) 和__floordiv__( )。//例如,如果您僅定義這兩個 將不起作用(請參閱下面的錯誤)。
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)
預期產出
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
有關這些特殊Python 函式的串列,請參閱此網站。
uj5u.com熱心網友回復:
您可能必須撰寫自己的庫來允許這種情況發生,制作一些簡單的東西可能并不難,當您收到該錯誤時會看到并將該數字分配給“無窮大”
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448615.html
標籤:python-3.x 运算符重载 压倒一切
