[問題]有關__XX__??

看板Python作者 (yorjing)時間15年前 (2009/06/23 23:27), 編輯推噓2(203)
留言5則, 2人參與, 最新討論串1/1
這幾天在摸Python 看到這個網頁的某個例子 http://pydoing.blogspot.com/2008/10/blog-post_1288.html 覺得很妙的是 class Point(): def __init__(self,x=0,y=0): self.x=x self.y=y def __str__(self): return "座標:(%d,%d)"%(self.x,self.y) def __add__(self,other): return Point(self.x+other.x,self.y+other.y) def __sub__(self,other): return Point(self.x-other.x,self.y-other.y) def __mul__(self,other): return self.x*other.x+self.y*other.y def __rmul__(self,other): return Point(other*self.x,other*self.y) 為什麼我如果輸入 >>> p1=Point(3,3) >>> p2=Point(5,5) >>> print p1+p2 為什麼會結果會跑出"座標:(8,8)"? 難道"+"會自動對應到"__add__(self,other)"嗎? 還是? 還有 function的用法怎麼會這樣用? 我被搞糊塗了... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.167.21.68 ※ 編輯: yorjing 來自: 118.167.21.68 (06/23 23:30)

06/23 23:49, , 1F
你要重載+就重寫__add__-就__sub__
06/23 23:49, 1F

06/23 23:51, , 2F
__add__是原本就有定義好由"+"對應的嗎?內建寫好得?
06/23 23:51, 2F

06/23 23:54, , 3F
內建寫好的,其他對應關係可以參考下面網址
06/23 23:54, 3F

06/23 23:55, , 5F
謝謝
06/23 23:55, 5F
文章代碼(AID): #1AGFH_ex (Python)