作者yorjing (yorjing)
看板Python
标题[问题]有关__XX__??
时间Tue Jun 23 23:27:58 2009
这几天在摸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)
1F:推 ya790206:你要重载+就重写__add__-就__sub__ 06/23 23:49
2F:→ yorjing:__add__是原本就有定义好由"+"对应的吗?内建写好得? 06/23 23:51
3F:推 ya790206:内建写好的,其他对应关系可以参考下面网址 06/23 23:54
5F:→ yorjing:谢谢 06/23 23:55