#魔术方法(三)——运算符魔术方法(普通算数操作符)

#魔术方法(三)——运算符魔术方法(普通算数操作符)

#普通算数操作符:
#1.__add__(self,other)魔术方法:在两个对象相加的时候执行的方法。
#2.__sub__(self,other)魔术方法:在两个对象相减的时候执行的方法。
#3.__mul__(self,other)魔术方法:在两个对象相乘的时候执行的方法。
#4.__floordiv__(self,other)魔术方法:在两个对象使用//运算的时候执行的方法。
#5.__truediv__(self,other)魔术方法:在Python3中使用/运算的时候会执行这个方法。
#6.__mod__(self,other)魔术方法:在使用%取模运算的时候执行的方法。

class Coordinate(object):
	def __init__(self,x,y):
		self.x = x
		self.y = y

	def __add__(self,other):
		x = self.x + other.x
		y = self.y + other.y
		new_coordinate = Coordinate(x,y)
		return new_coordinate

	def __sub__(self,other):
		x = self.x - other.x
		y = self.y - other.y
		new_coordinate = Coordinate(x,y)
		return new_coordinate

	def __mul__(self,other):
		x = self.x * other.x
		y = self.y * other.y
		new_coordinate = Coordinate(x,y)
		return new_coordinate 

	def __truediv__(self,other):
		x = self.x / other.x
		y = self.y / other.y
		new_coordinate = Coordinate(x,y)
		return new_coordinate

	def __floordiv__(self,other):
		x = self.x // other.x
		y = self.y // other.y
		new_coordinate=Coordinate(x,y)
		return new_coordinate

	def __mod__(self,other):
		x = self.x % other.x
		y = self.y % other.y
		new_coordinate=Coordinate(x,y)
		return new_coordinate

	def __str__(self):
		return "(%s,%s)"%(self.x,self.y)

c1 = Coordinate(1,2)
c2 = Coordinate(2,3)
c3 = c1 % c2
print(c3)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值