Adam Obaid
Adam Obaid

Reputation: 33

How to return list of class objects sorted based on attribute value

I'm creating a class called Game. The objects of the class have the following attributes:

This is the class:

class Game:


    num_of_objects = 0

    def __init__(self, name, genre, year=1990, month=1, day=1):
        """
        Class Constructure: Returns a Game object whose parameters are:
        name: String
        genre: String
        data: YYYY-MM-DD
        """   
        self.name = name
        self.genre = genre
        self.year = year
        self.month = month
        self.day = day
        self.release_date = self.year + '-' + self.month + '-' + self.day
        Game.num_of_objects += 1 

    def __repr__(self):
        return str(self)

    def games_by_year():
          print [Game.genre for Game in x]

    def games_by_genre():
        pass

    def games_starting_with():
        pass

I would like to create a class method, that returns a list of the Games by genre, and another method that returns a list of games by year. The games in this scenario are just class objects:

Halo = Game('Halo', 'shooter', '2019', '11', '12')

Also, is there a better way to deal with the date? I'd like to be in the format YYYY-MM-DD

Upvotes: 2

Views: 84

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599590

You need to actually store the games somewhere when you create them. A class-level list would work:

class Game:

    num_of_objects = 0
    games = []

    def __init__(self, name, genre, year=1990, month=1, day=1):
        ...
        self.games.append(self)

You can probably remove the num_of_objects counter, since that is trivially found from len(self.games). (And note, since you're mutating rather than reassigning the games object, you can refer to it directly via self.)

Now, your actual methods need to be classmethods, which accept cls as the first parameter:

@classmethod
def games_by_year(cls):
      return sorted(cls.games, key=lambda g: g.year)

@classmethod
def games_by_genre(cls):
      return sorted(cls.games, key=lambda g: g.genre)

Upvotes: 1

Related Questions