简体   繁体   中英

Instantiate a class with a list

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?

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)

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=[]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM