类分布错误

时间:2013-02-08 20:01:26

标签: python python-3.x

这是班级:

class Player:
    #variables
    hand = []
    name = 'Test Player'
    #functions
    def take(self, card): #allows player to take a card
        self.hand.append(card)
    def __str__(self):
        msg = self.name
        if len(self.hand) > 0:
            msg = msg + "\nIn hand:"
            for card in self.hand:
                msg = msg + ' ' + card.short_name
        return msg

这是功能:

def deal(players):
    deck = Deck.generate_deck()
    if len(players) <= 4:
        for player in players:
            for cards in range (0, 7):
                card = random.choice(deck)
                player.take(card)
                deck.remove(card)
    else:
        for player in players:
            for cards in range (0, 5):
                card = random.choice(deck)
                player.take(card)
                deck.remove(card)
    return deck

这是问题所在。当我打电话给五名球员发牌时,这就是我得到的。

Player 1
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

Player 2
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

Player 3
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

Player 4
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

Player 5
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

P.S。之后的数字在我的测试代码中是一个很小的调试,没有任何影响。

1 个答案:

答案 0 :(得分:3)

您的问题是您的hand = []列表已附加到班级;它是一个类属性,并在实例之间共享。

__init__方法中为每位玩家创建一个新列表:

class Player:
    def __init__(self):
        self.hand = []