storearea

导航

Python比较函数__cmp__

#!/usr/bin/python

class my_type(object):
    def __init__(self, v): 
        self.value = v 
    def __cmp__(self, v2):
        if self.value > v2.value:
            return 1
        elif self.value == v2.value:
            return 0
        else:
            return -1
 
if __name__ == '__main__':
    a = my_type(3)
    b = my_type(4)
    print a > b
    print cmp(a,b)

 直接判断a>b内部,调用__cmp__(),如果a>b则返回True,否则返回False。

调用cmp的时候,同样会调用__cmp__(),如果a>b返回1,a==b返回0,否则返回-1.

posted on 2014-12-12 22:26  store  阅读(250)  评论(0编辑  收藏  举报