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).
来自:
import operatorclass 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 -10000x=iint(1)y=iint(2)print x
结果:
>>> 1 is less than 2100002 is not less than 1-10000