- __add__(self,other)魔术方法:加法运算
- __sub__(self,other)魔术方法:减法运算
- __mul__(self,other)魔术方法:乘法运算
- __turediv__(self,other)魔术方法:除法运算(Python3)
- __div__(self,other)魔术方法:除法运算
- __mod__(self,other)魔术方法:取余运算
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # 加法操作
new_coordinate = Coordinate(self.x+other.x, self.y+other.y)
return new_coordinate
""" 方法2:
x = self.x + other.x
y = self.y + other.y
return Coordinate(x, y)
"""
def __sub__(self, other): # 减法操作
x = self.x - other.x
y = self.y - other.y
return Coordinate(x, y)
def __mul__(self, other): # 乘法操作
x = self.x * other.x
y = self.y * other.y
return Coordinate(x, y)
def __truediv__(self, other): # 除法操作 (python2中不太一样,使用__div__方法)
x = self.x / other.x
y = self.y / other.y
return Coordinate(x, y)
def __mod__(self, other): # 取余运算
x = self.x % other.x
y = self.y % other.y
return Coordinate(x, y)
def __str__(self):
return "Coordinate({},{})".format(self.x,self.y)
c1 = Coordinate(1, 2)
c2 = Coordinate(3, 4)
print(c1 + c2) # Coordinate(4,6)
print(c1 - c2) # Coordinate(-2,-2)
print(c1 * c2) # Coordinate(3,8)
print(c1 / c2) # Coordinate(0.3333333333333333,0.5)
print(c1 % c2) # Coordinate(1,2)