Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of objects using an object function

I have a class players which have their name and experience as private attributes. I have 2 functions that returns each of them.

class Player:
    def __init__(self,name,experience):
        self.__name=name
        self.__experience=experience

    def get_name(self):
        return self.__name

    def get_experience(self):
        return self.__experience

    def __str__(self):
        return(self.__name + " " + str(self.__experience))

I created a game class that gets a list of players and it has a function that sorts the players based on their experience.

class Game:
    def __init__(self, players_list):
        self.players_list=players_list
        
    def sort_players_based_on_exp(self):
        # I don't know how to sort them

I know that the sort() method has a parameter key, but I don't know how to use that in this case.

like image 772
Itzz_CJ Avatar asked Dec 17 '25 23:12

Itzz_CJ


1 Answers

The sort and sorted methods can take a callable of a single argument as a key function, and will sort on the results of it. So you need a callable that returns the attribute you want to sort on, given a Player instance. In this case, that's your accessor method.

def sort_players_based_on_exp(self):
    return sorted(self.players_list, key=Player.get_experience)

When sorting on an attribute, the operator module has useful methods that are faster than a lambda to resolve an attribute key, but as noted in comments you don't need them here. See the "Sorting HOW TO" docs for some more examples and explanation.

As a side note - in general Python doesn't bother with obfuscating attributes and using getters and setters. The Python idiom would be to just have experience present as an attribute on the class. If you need to change the behavior later, you can replace bare attribute access by something functional with the @property decorator while maintaining the access syntax.

like image 139
Peter DeGlopper Avatar answered Dec 20 '25 12:12

Peter DeGlopper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!