-2

So my class is

class Student:
        
    raise_amt = 1.8
    no_of_students = 0
    def __init__(self, id, name, age, salary):
        self.id = id
        self.name = name
        self.age = age
        self.salary = salary
        
        
        Student.no_of_students+=1
        
    
    def __repr__(self):
        return "Student({}, {}, {}, {})".format(self.id, self.name, self.age, self.salary)
    
    
    def __str__(self):
        return "Student user: {}, name:{}, age:{}".format(self.id, self.name, self.age)   

And I have created an object with 3 objects

s1 = Student(10, "Pranav", 21, 1200)
s2 = Student(20, "Pranav", 22, 1500)
s3 = Student(30, "tejas", 22, 5999)

students = []

students.append(s1)
students.append(s2)
students.append(s3)


The sort function given is

students.sort(key = lambda x:x.name)

I WANT TO SORT THE LIST IN SUCH A WAY THAT IF NAMES ARE EQUAL, IT SHOULD THEN CHECK AGE AND IF THAT IS EQUAL ASWELL THEN SALARY

Basically the equivalent of the comparator class in Java

U13-Forward
  • 69,221
  • 14
  • 89
  • 114

2 Answers2

0

To achieve what you want just return sorting key as a tuple of necessary fields:

students.sort(key = lambda x: (x.name, x.age, x.salary))

Try full working code here online .

Arty
  • 14,883
  • 6
  • 36
  • 69
0

The best way is to implement magic methods like __gt__ (https://docs.python.org/3/reference/datamodel.html#object.__gt__) in your class and let the standard operators do what they are supposed to do. The standard sort function will work like a charm letting the objects know how to compare themselves.

MetallimaX
  • 594
  • 4
  • 13