看板 Python 關於我們 聯絡資訊
這幾天在摸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)
ya790206:你要重載+就重寫__add__-就__sub__ 06/23 23:49
yorjing:__add__是原本就有定義好由"+"對應的嗎?內建寫好得? 06/23 23:51
ya790206:內建寫好的,其他對應關係可以參考下面網址 06/23 23:54
yorjing:謝謝 06/23 23:55