用列表实例化 class

Instantiate a class with a list

我有一个 class 叫做 Player...

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

...我有一个 class 游戏

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

目前我可以实例化 Game class 有:

    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])

然而,理想情况下,我更愿意用类似的东西实例化 Game class:

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

我怎样才能做到这一点?

解法:

创建/实例化 Game class 时,通过:

game = Game(player_list)

我没有首先创建任何 Player 对象。由于我的 Game class 需要玩家存在,所以失败并给出错误:


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

这是因为,根据Game那里没有Players;因此 Game class 没有 score 可以使用。

通过此命令实例化 Game

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

我现在正在实例化 Game 同时创建必要的 Player 对象。

有许多正确答案展示了执行此操作的不同方法。

为此,您可以在 Game 的构造函数中实例化玩家。

类似于:

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')]) 应该可以。添加更多玩家到列表

显而易见的解决方案(在评论中指出)是创建 Player 对象的列表,以便将其传递给 Game:

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

另一种选择是将其封装为 class 方法

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)