你怎麼能使用__add__
功能Python類,添加2D點
(1,2)+(2,3) = (3,5)
def __add__(self, other):
return Point((lambda x,y:x+y),self,other)
是這樣想的方式添加兩個值? 什麼是可能的錯誤!
你怎麼能使用__add__
功能Python類,添加2D點
(1,2)+(2,3) = (3,5)
def __add__(self, other):
return Point((lambda x,y:x+y),self,other)
是這樣想的方式添加兩個值? 什麼是可能的錯誤!
這已經很接近,除非你需要return NotImplemented
,如果它不是一個Point
:
def __add__(self, other):
if not isinstance(other, Point):
return NotImplemented
return Point(self.x + other.x, self.y + other.y)
如果我正確認識你,我可能會做這種方式:
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
你的問題有點含糊,你不提供有關Point
類細節,因此這是一個有點困難完全明白你在問什麼。
具體來說,我不明白構造函數的lambda參數的目的。我想我明白它在做什麼,但我不確定我能否看到這種構造函數將成爲表達操作的有用方式。
請記得按一下旁邊的複選標記接受解答您的疑問。你也應該爲你的舊問題做這個 - 我看到其中有幾個人有你沒有接受的好答案。 – agf