[英]Overloading Addition, Subtraction, and Multiplication Operators
您如何 go 重載加法、減法和乘法運算符,以便我們可以加、減和乘以不同或相同大小的兩個向量? 例如,如果向量的大小不同,我們必須能夠根據最小的向量大小對兩個向量進行加、減或乘?
我創建了一個 function 允許您修改不同的向量,但現在我正在努力使運算符超載並且不知道從哪里開始。 我將粘貼下面的代碼。 有任何想法嗎?
def __add__(self, y): self.vector = [] for j in range(len(self.vector)): self.vector.append(self.vector[j] + y.self.vector[j]) return Vec[self.vector]
您為 class 定義__add__
、 __sub__
和__mul__
方法,就是這樣。 每個方法將兩個對象( +
/ -
/ *
的操作數)作為 arguments 並期望返回計算結果。
這個問題的公認答案沒有錯,但我添加了一些簡短的片段來說明如何使用它。 (請注意,您也可以“重載”該方法來處理多種類型。)
"""Return the difference of another Transaction object, or another class object that also has the `val` property.""" class Transaction(object): def __init__(self, val): self.val = val def __sub__(self, other): return self.val - other.val buy = Transaction(10.00) sell = Transaction(7.00) print(buy - sell) # 3.0
"""Return a Transaction object with `val` as the difference of this Transaction.val property and another object with a `val` property.""" class Transaction(object): def __init__(self, val): self.val = val def __sub__(self, other): return Transaction(self.val - other.val) buy = Transaction(20.00) sell = Transaction(5.00) result = buy - sell print(result.val) # 15
"""Return difference of this Transaction.val property and an integer.""" class Transaction(object): def __init__(self, val): self.val = val def __sub__(self, other): return self.val - other buy = Transaction(8.00) print(buy - 6.00) # 2
文檔有答案。 基本上,當您添加或多個等時,object 上會調用一些函數,例如__add__
是正常的添加 function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.