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

    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

 

posted @ 2013-10-30 20:32  LisPythoniC  阅读(429)  评论(0编辑  收藏  举报