Python rich comparisons 自定义对象比较过程和返回值

本文介绍如何在Python中为自定义类实现比较运算符(__lt__,__le__,__gt__,__ge__,__eq__,__ne__),并提供了一个具体示例。通过使用这些特殊方法,可以为自定义类型增加丰富的比较机制。

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

    Classes wishing to support the rich comparison mechanisms must add
    one or more of the following new special methods:

             def __lt__(self, other):
                ...
             def __le__(self, other):
                ...
             def __gt__(self, other):
                ...
             def __ge__(self, other):
                ...
             def __eq__(self, other):
                ...
             def __ne__(self, other):
                ...

    Each of these is called when the class instance is the on the
    left-hand-side of the corresponding operators (<, <=, >, >=, ==,
    and != or <>). The argument other is set to the object on the
    right side of the operator. The return value of these methods is
    up to the class implementor (after all, that's the entire point of
    the proposal).

来自:http://www.python.org/dev/peps/pep-0207/

import operator

class iint(int):
    def __init__(self,n):
        int.__init__(n)
        self.v=n
    def __lt__(self,otr):
        if operator.lt(self.v,otr):
            print '%s is less than %s' %(self.v,otr)
            return 10000
        print '%s is not less than %s' %(self.v,otr)
        return -10000

x=iint(1)
y=iint(2)
print x<y
print y<x

结果:

>>> 
1 is less than 2
10000
2 is not less than 1
-10000

 

转载于:https://www.cnblogs.com/xiangnan/p/3397694.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值