二元运算符的魔术方法

  • 二元运算符的魔术方法
  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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值