[問題]有關__XX__??
這幾天在摸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
06/23 23:49, 1F
→
06/23 23:51, , 2F
06/23 23:51, 2F
推
06/23 23:54, , 3F
06/23 23:54, 3F
→
06/23 23:54, , 4F
06/23 23:54, 4F
→
06/23 23:55, , 5F
06/23 23:55, 5F