增量赋值运算的魔术方法

  • 增量赋值的运算魔术方法
  1. __iadd__(self,other)魔术方法:在给对象做+=运算的时候会执行的方法。
  2. __isub__(self,other)魔术方法:在给对象做-=运算的时候会执行的方法。
  3. __imul__(self,other)魔术方法:在给对象做*=运算的时候会执行的方法。
  4. idiv(self,other)魔术方法:在给对象做/=运算的时候会执行的方法。(Python2)
  5. __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)

猜你喜欢

转载自blog.csdn.net/qq_43539055/article/details/85038887