`
fiftyk
  • 浏览: 22524 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
文章分类
社区版块
存档分类
最新评论

Python运算符重载

阅读更多
#coding=utf-8
class Line:
	def __init__(self,p1,p2):
		self.start = p1
		self.end = p2

	def __sub__(self,p):
		if isinstance(p,Point):
			if p is self.start:
				return self.end
			if p is self.end:
				return self.start
class Point:
	def __init__(self,x,y):
		self.x = x
		self.x = x

	def __add__(self,p):
		if isinstance(p,Point):
			return Line(self,p)

if __name__ == '__main__':
	p1 = Point(1,2)
	p2 = Point(2,3)

	line = p1 + p2# 两个点相加 通过__add__方法
	print l
	#>><__main__.Line instance at 0x02220738>
	
	print line - p1# 线减去一个点 通过__sub__方法
	#>><__main__.Point instance at 0x02220710>
 
0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics