#魔术方法(三)——运算符魔术方法(普通算数操作符)
#普通算数操作符:
#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)
#魔术方法(三)——运算符魔术方法(普通算数操作符)
最新推荐文章于 2024-01-12 14:00:00 发布