0

Could anyone please find out what is wrong going on here? cmp is not being invoked. sorted(list, key=...) or similar works fine. However, that is also not overriding cmp method.

My aim is to sort by multiple keys. I have composition relationship as well. Student can have list of another custom object and so on. What is best way to do? I am thinking to do something like compareTo or comparing or Comparator (Stream API) in Java in functional way. There could be default sorting.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.

class Student(object):
    def __init__(self, name, mark):
         self.name = name
         self.mark = mark

    def __cmp__(self, other):
        if self.name < other.name:
           return -1
        elif self.name > other.name:
           return 1
        else:
           return 0
        #return self.name.__cmp__(other.name)

student_list = [
Student(name="cccc", mark=10),
Student(name="aaaa", mark=5),
Student(name="dddd", mark=7)
]

student_list = sorted(student_list)

TypeError: unorderable types: Student() < Student()

Pati Ram Yadav
  • 815
  • 1
  • 8
  • 22

2 Answers2

1

In Python 3 __cmp__ is deprecated. For sorting use __lt__ instead:

class Student(object):
    def __init__(self, name, mark):
         self.name = name
         self.mark = mark

    def __lt__(self, other):
        return self.name < other.name

    def __repr__(self):
        return self.name

student_list = [
Student(name="cccc", mark=10),
Student(name="aaaa", mark=5),
Student(name="dddd", mark=7)
]

print(sorted(student_list)) # [aaaa, cccc, dddd]
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

__cmp__() is obsolete and is no longer supported. The correct way to do it is to override as many of __lt__(), __le__() and __eq__() as required.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358