How to sort Objects objects in python
This article shows you how to sort Objects objects in python. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Create a new python file named py3_oop_sort.py, and write the operation code in this file:
Class Employee: def _ _ init__ (self,name,age,pay): self.name = name self.age = age self.pay = pay def _ repr__ (self): return'({}, {}, {}) '.format (self.name,self.age,self.pay)
# instantiate three objects emp_1 = Employee ('TBag',25,50000) emp_2 = Employee (' McUser',30,60000) emp_3 = Employee ('Helly',42,80000) # store them in the list list emps = [emp_1,emp_2,emp_3] # define a sort function Return value here # you can specify what attribute to sort by def e_sort (emp): return emp.name# uses sorted to sort sort_emps = sorted (emps,key=e_sort) print (sort_emps)
Running result:
[(Helly,42,80000), (McUser,30,60000), (TBag,25,50000)] the above is how to sort Objects objects in python. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.