我一直在嘗試使用python中的類,使一個新的變數型別成為四元數。 我已經知道了如何讓它添加一個整數或浮點數,但我不知道如何讓它將四元數添加到浮點數/整數。我只寫了一個月的代碼,試圖學習如何編程來制作一個 "不同數字系統的通用計算器 "或UCFDNS。我還想讓它對__sub__、__mul__、__div__起作用。這可能嗎?
class Quaternion。
def __init__(self, a, b, c, d)。
self.real = a
self.imag1 = b
self.imag2 = c
self.imag3 = d
#addition[/span]。
def __add__(self, other):
if type(other) == int or type(other) == float:
other1 = Quaternion(other,0,0,0)
return other1 self
elif type(other)==type(self):
return Quaternion(other.real self.real,other.imag1 self.imag1,other.imag2 self.imag2, other.imag3 self.imag3)
else:
print('You can' "' " 't add a', type(other),' with a QuaternionNumber')
import sys
sys.exit(1)
uj5u.com熱心網友回復:
一個正確的 __add__ 的實作應該回傳特殊的常量 NotImplemented 如果它不知道如何處理加法。所有的 Python 內置類的撰寫都是為了遵守這一點。如果 __add__ 回傳 NotImplemented,那么 Python 將在右側呼叫 __radd__。所以你需要做的就是實作 __radd__ 來做與 __add__ 基本相同的事情,你的類將神奇地開始與內置型別一起作業。
注意,為了尊重其他做同樣事情的人,如果你不能處理這個操作,你也應該回傳NotImplemented,所以你的__add__(和__radd__)應該看起來像
def __add__(self, other):
if type(other) == int or type(other) == float:
other1 = Quaternion(other,0,0,0)
return other1 self
elif type(other)==type(self):
return ComplexNumber(other.real self.real,other.imag1 self.imag1,other.imag2 self.imag2, other.imag3 self.imag3)
else:
return NotImplemented。
還要記住,__add__和__radd__看起來是一樣的,因為加法是交換的。但是__sub__和__rsub__,例如,看起來會有所不同,因為在__rsub__中,self是減法運算的右手邊,而且順序很重要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310492.html
標籤:
