首页 > 代码库 > python build-in function __cmp__

python build-in function __cmp__

读王纯业前辈的笔记遇到个很坑的例子

A namespace is a mapping from names to objects

>>> class a:
    def __cmp__(self,other):
        if other > 0 : print ‘other > 0‘ ;return -1
        elif other < 0 : print ‘other < 0‘ ;return 1
        else : print ‘other==0‘; return 0

        
>>>
>>>
>>>
>>> o=a()
>>>
>>> if (o > 10) : print ‘tt‘

other > 0
>>> if (o < 10) : print ‘tt‘

other > 0
tt
>>>
>>>
>>>
>>>
>>> if (o > -10) : print ‘tt‘

other < 0
tt
>>> if (o < -10) : print ‘tt‘

other < 0

__cmp__ 中return的3个值 1,-1,0

执行过程:

1,根据other的值确定执行那一条,结果是返回1,-1,或0

2,判断返回值是否和表达式中的符号匹配,匹配返回True,不匹配返回False

 

python build-in function __cmp__