二元运算符的魔术方法

  • 二元运算符的魔术方法
  1. __add__(self,other)魔术方法:加法运算
  2. __sub__(self,other)魔术方法:减法运算
  3. __mul__(self,other)魔术方法:乘法运算
  4. __turediv__(self,other)魔术方法:除法运算(Python3)
  5. __div__(self,other)魔术方法:除法运算
  6. __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)

猜你喜欢

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