vendredi 15 octobre 2021

What's best way to pass different insances of object to multiple classes?

States class is a superclass for Game and MainMenu because they gonna use attributes with the same names. In the project I'm gonna use only one instance of Game and MainMenu class. GameData is a class which loads(from files) and store data like images, sounds etc. and it's attributes are read-only. I'd like to pass GameData object to the Game and MainMenu instances and I wonder, if my solution where I put it in the superclass is correct or there's maybe better way?

from game_data import GameData


class States:
    """Superclass for each state"""
    game_data = GameData()  # Is it correct and 'pythonic'?

    def __init__(self):
        self.done = False
        self.next = None
        self.quit = False
        self.previous = None


class Game(States):
    def __init__(self):
        States.__init__(self)

    def some_method(self):
        pass # Here I'm gonna use game_data


class MainMenu(States):
    def __init__(self):
        States.__init__(self)

    def some_method(self):
        pass # Here I'm gonna use game_data

Other solution but I think it's incorrect because it's not optimal(2 instances of GameData()):

from game_data import GameData


class States:
    """Superclass for each state"""
    def __init__(self):
        self.done = False
        self.next = None
        self.quit = False
        self.previous = None


class Game(States):
    def __init__(self):
        States.__init__(self)
        self.game_data = GameData()  # First instance

    def some_method(self):
        pass # Here I'm gonna use self.game_data


class MainMenu(States):
    def __init__(self):
        States.__init__(self)
        self.game_data = GameData()  # Second instance

    def some_method(self):
        pass # Here I'm gonna use self.game_data

Or maybe it should be passed as an argument?:

from game_data import GameData


class States:
    """Superclass for each state"""
    def __init__(self):
        self.done = False
        self.next = None
        self.quit = False
        self.previous = None


class Game(States):
    def __init__(self, game_data):  # As arg
        States.__init__(self)
        self.game_data = game_data  # Assignment
    def some_method(self):
        pass # Here I'm gonna use self.game_data


class MainMenu(States):
    def __init__(self, game_data):  # As arg
        States.__init__(self)
        self.game_data = game_data  # Assignment

    def some_method(self):
        pass # Here I'm gonna use self.game_data


game_data = GameData()
game = Game(game_data)
main_menu = MainMenu(game_data)

Is one of these solutions correct or it should be done in another way?

Aucun commentaire:

Enregistrer un commentaire