Home > Blockchain >  Instantiate a class with a list
Instantiate a class with a list

Time:12-21

I have a class called Player...

class Player:
    def __init__(self,name,score=6):
        self.name=name
        self.score=score
        self.roll = 0

...And I have a class called Game

class Game:
    def __init__(self,players):
        self.current_round = 1
        self.players=players
        self.winner_round= None
        self.player_names=[]

Currently I can instantiate the Game class with:

    player_1=Player('Kid1')
    player_2=Player('Kid2')
    player_3=Player('Mom')
    player_4=Player('Dad')

    game = Game([player_1,player_2,player_3,player_4])

However, ideally I'd prefer to instantiate the Game class with something like:

player_list=['Kid1','Kid2','Mom','Dad']
game = Game(player_list)

How might I achieve this?

Solution:

When creating / instantiating the Game class, via:

game = Game(player_list)

I had not created any Player objects first. Since my Game class required players to exist, it was failing and giving the error of:


AttributeError: 'str' object has no attribute 'score'

This is because, according to Game there where no Players; hence there was no score for the Game class to use.

By instantiating Game via this command:

game=Game([Player(name) for name in player_list])

I was now instantiating Game and creating the necessary Player objects at the same time.

There are many correct answers that demonstrate different ways to do this.

CodePudding user response:

The obvious solution (pointed out in the comments) is to create the list of Player objects in order to pass it to Game:

player_list = ['Kid1', 'Kid2', 'Mom', 'Dad']
game = Game([Player(s) for s in player_list])

Another option is to encapsulate this as a class method

class Game:
    def __init__(self, players):
        self.current_round = 1
        self.players = players
        self.winner_round = None

    @classmethod
    def from_names(cls, player_names):
        return cls([Player(s) for s in player_names])


player_list = ['Kid1', 'Kid2', 'Mom', 'Dad']
game = Game.from_names(player_list)

CodePudding user response:

To do it, you can instantiate the player in Game's constructor.

Something like :

class Game:
    def __init__(self,players):
        self.current_round = 1
        self.players=[Player(name) for name in players]
        self.winner_round= None
        self.player_names=[]

CodePudding user response:

game = Game([Player ('jack')]) should work. Add more players to the list

  • Related