Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Multiple One-Argument Constructors

Tags:

python

I have a Game class which has a field that's a Board object. I currently make a Game by passing in a string encoding information about the game and making the Board object.

However, I now have a bunch of Board objects and want to make a new constructor that takes in the Board object directly.

Here's my current constructor:

def __init__(self, game_string):
    self.single_list = game_string.split(",")
    self.board = self.parse_game_string(game_string)
    self.directions = self.get_all_directions()
    self.red_number_of_streaks = self.get_number_of_streaks("R")
    self.black_number_of_streaks = self.get_number_of_streaks("B")

But now I have the board object, so I'd like to just do:

def __init__(self, board):
    self.board = board
    self.directions = self.get_all_directions()
    self.red_number_of_streaks = self.get_number_of_streaks("R")
    self.black_number_of_streaks = self.get_number_of_streaks("B")

I don't think Python will know how to distinguish between these two constructors. I could determine what to do based on the type of argument? Something like:

if isinstance(str): # usual constructor functionality elif isinstance(Game): # new constructor functionality

Is there a better way?

Thanks!

like image 889
anon_swe Avatar asked Feb 13 '26 19:02

anon_swe


1 Answers

I would do it like this:

class Game:
    def __init__(self, board):
        ...

    @classmethod
    def from_string(cls, game_string):
        board = cls.parse_game_string(game_string)
        game = cls(board)
        game.something = 5

        return game

    @staticmethod
    def parse_game_string(game_string):
        ...

        return Board(...)

Game.from_string would then construct an instance of Game out of a string, using the default Game initializer which accepts a Board object.

You will have to make Game.parse_game_string a static method for it to be usable from the Game.from_string class method.

like image 200
Blender Avatar answered Feb 15 '26 09:02

Blender



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!