- __iadd__(self,other)魔术方法:在给对象做+=运算的时候会执行的方法。
- __isub__(self,other)魔术方法:在给对象做-=运算的时候会执行的方法。
- __imul__(self,other)魔术方法:在给对象做*=运算的时候会执行的方法。
- idiv(self,other)魔术方法:在给对象做/=运算的时候会执行的方法。(Python2)
- __itruediv__(self,other)魔术方法:在给对象做 /=运算的时候会执行的方法。(Python3)
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __iadd__(self, other): # 执行 += 运算
x = self.x + other
y = self.y + other
return Coordinate(x, y)
def __isub__(self, other): # 执行 -= 运算
x = self.x - other
y = self.y - other
return Coordinate(x, y)
def __imul__(self, other): # 执行 *= 运算
x = self.x * other
y = self.y * other
return Coordinate(x, y)
def __itruediv__(self, other): # 执行 /= 运算(python3)
x = self.x / other
y = self.y / other
return Coordinate(x, y)
def __str__(self):
return "Coordinate({},{})".format(self.x,self.y)
c1 = Coordinate(1, 2)
for i in range(5):
c1 += 1
print(c1)
for i in range(5):
c1 -= 1
print(c1)
for i in range(5):
c1 /= 2
print(c1)