在python中为类添加自定义的运算符

文章介绍了如何在Python中通过定义特殊方法如__add__,__sub__等来自定义类的行为,例如创建一个表示星期的类,使得可以对星期进行加减运算。同时强调了反向运算符如__radd__的使用,并指出不应为类定义__rsub__,因为星期类中3-week可能无实际意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

运算符

正向运算符

正向运算符,这里指的是自身为左操作数的运算符

1,加法运算符(+) __add__(self, other): 定义两个对象相加

2,减法运算符(-) __sub__(self, other): 定义两个对象相减

3,乘法运算符(*) __mul__(self, other): 定义两个对象相乘

4,除法运算符(/) __truediv__(self, other): 定义两个对象相除

5,取整除法运算符(//) __floordiv__(self, other): 定义两个对象整除

6,取模运算符(%) __mod__(self, other): 定义两个对象取模

7,幂运算符(**) __pow__(self, other): 定义两个对象求幂

8,小于运算符(<)__lt__(self, other): 定义对象小于

9,大于运算符(>)__gt__(self, other): 定义对象大于

10,等于运算符(==)__eq__(self, other): 定义对象相等

反向运算符

反向运算符,这里指的是自身为右操作数的运算符 

1,__radd__(self, other):对应于加法运算符的右侧操作数

2,__rsub__(self, other): 对应于减法运算符的右侧操作数

3,__rmul__(self, other): 对应于乘法运算符的右侧操作数

4,__rtruediv__(self, other): 对应于除法运算符的右侧操作数

5,__rfloordiv__(self, other): 对应于取整除法运算符的右侧操作数

6,__rmod__(self, other): 对应于取模运算符的右侧操作数

7,__rpow__(self, other): 对应于幂运算符的右侧操作数

使用自定义运算符的例子

以星期为例

class Week:

    def __init__(self, today):
        self.__week = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
        if isinstance(today, str) and today in self.__week:
            self.__today = self.__week.index(today)
        elif isinstance(today, int) and 1 <= today <= 7:
            self.__today = today - 1
        elif isinstance(today, int):
            raise ValueError("按照我们这里的规矩,1-7分别代表星期一到星期七,不可以使用其他数字")
        else:
            raise ValueError("非法的输入格式,请输入1-7代表星期一到星期日")

    @property
    def today(self):
        return self.__week[self.__today]

    def __add__(self, other):
        if not isinstance(other, int):
            raise ValueError("你是故意的吧?我们需要一个整数!")
        return Week(self.__week[(self.__today + other) % 7])

    def __sub__(self, other):
        if not isinstance(other, int):
            raise ValueError("你是故意的吧?我们需要一个整数!")
        return Week(self.__week[(self.__today - other) % 7])


if __name__ == "__main__":
    w1 = Week(1)
    print(w1.today)
    w2 = w1 + 3
    print(w2.today)

为星期添加上反向的运算符

class Week:

    def __init__(self, today):
        self.__week = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
        if isinstance(today, str) and today in self.__week:
            self.__today = self.__week.index(today)
        elif isinstance(today, int) and 1 <= today <= 7:
            self.__today = today - 1
        elif isinstance(today, int):
            raise ValueError("按照我们这里的规矩,1-7分别代表星期一到星期七,不可以使用其他数字")
        else:
            raise ValueError("非法的输入格式,请输入1-7代表星期一到星期日")

    @property
    def today(self):
        return self.__week[self.__today]

    def __add__(self, other):
        if not isinstance(other, int):
            raise ValueError("你是故意的吧?我们需要一个整数!")
        return Week(self.__week[(self.__today + other) % 7])

    def __sub__(self, other):
        if not isinstance(other, int):
            raise ValueError("你是故意的吧?我们需要一个整数!")
        return Week(self.__week[(self.__today - other) % 7])

    def __radd__(self, other):
        return self.__add__(other)


if __name__ == "__main__":
    w1 = Week(1)
    print(w1.today)
    w2 = 3 + w1
    print(w2.today)

需要额外注意的是,如果添加这样的代码,这样的做法是不对的

def __rsub__(self, other):
    return self.__sub__(other)

因为很显然,week - 3和3 - week不是一回事,并且,在这个例子中,3 - week可能没有明确的实际意义,因此不应当添加__rsub__

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值