-
-
Save IndhumathyChelliah/d404fd5d078e940e17c124a626219728 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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