python3 cmp实现

  • Post author:
  • Post category:python




python3移除了

cmp()

函数,但提供了六个丰富的比较运算符,详见

此处

import operator       #首先要导入运算符模块
operator.gt(1,2)      #意思是greater than(大于)
operator.ge(1,2)      #意思是greater and equal(大于等于)
operator.eq(1,2)      #意思是equal(等于)
operator.le(1,2)      #意思是less and equal(小于等于)
operator.lt(1,2)      #意思是less than(小于)



PY3__cmp__ mixin类:

import sys
PY3 = sys.version_info[0] >= 3
if PY3:
    def cmp(a, b):
        return (a > b) - (a < b)
    # mixin class for Python3 supporting __cmp__
    class PY3__cmp__:   
        def __eq__(self, other):
            return self.__cmp__(other) == 0
        def __ne__(self, other):
            return self.__cmp__(other) != 0
        def __gt__(self, other):
            return self.__cmp__(other) > 0
        def __lt__(self, other):
            return self.__cmp__(other) < 0
        def __ge__(self, other):
            return self.__cmp__(other) >= 0
        def __le__(self, other):
            return self.__cmp__(other) <= 0
else:
    class PY3__cmp__:
        pass

class YourClass(PY3__cmp__):
	'''自定义类,可以用list.sort函数或者sorted函数来实现排序。'''
	def __init__(self, name, age):
        self.name = name
        self.age = age
    def __cmp__(self, other):
        return cmp(self.age, other.age)


cmp()

函数实现的注解:

bool

仅仅是一个

int

子类,那么

True



False

可以理解为

1



0

区别。因为如果第一个参数小于第二个参数,cmp返回负值,如果参数相等则返回0,否则返回正值,可以看到

False - False == 0



True - False == 1



False - True == -1

为cmp提供正确的返回值。


本文受益于此



版权声明:本文为A156348933原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。