Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created June 24, 2020 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IndhumathyChelliah/d404fd5d078e940e17c124a626219728 to your computer and use it in GitHub Desktop.
Save IndhumathyChelliah/d404fd5d078e940e17c124a626219728 to your computer and use it in GitHub Desktop.
class Student:
def __init__(self,name,rollno,grade):
self.name=name
self.rollno=rollno
self.grade=grade
def __repr__(self):
return f"{self.name}-{self.rollno}-{self.grade}"
#Initializing Student Objects
s1=Student("karthi",15,"second")
s2=Student("Indhu",12,"fifth")
s3=Student("Sarvesh",21,"first")
#Creating list of student objects
s4=[s1,s2,s3]
#Sorting list of objects
#Deifining function which will return rollno of the object
def sort_key(s):
return s.rollno
#sorting list of objects without specifying key parameter.It raises TypeError
print (sorted(s4))
#Output:TypeError: '<' not supported between instances of 'Student' and 'Student'
#Sorting list of objects based on attribute:rollno
s5=sorted(s4,key=sort_key)
print (s5)
#Output:[Indhu-12-fifth, karthi-15-second, Sarvesh-21-first]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment