无法将对象附加到实例变量(列表)

Cannot append an object to an instance variable(list)

我正在努力学习 python 并且正在尝试制作二十一点游戏。我创建了一个 Person class,其中有一个名为 self.hand 的实例变量。 self.hand 是一个空列表,应该包含 2 张初始卡片,从那里开始,任何需要卡片的玩家都会通过 append 方法收到一张卡片。但是,由于某种原因,这对我不起作用。有人请帮助它已经困扰我好几天了!!

我已经尝试创建 get_add_card(获取附加卡)实例方法并尝试手动将新卡对象附加到人员手牌列表。没有任何效果。

第一段代码是 Person class。在那个 class 中,我将 self.hand 定义为一个列表,该列表最初将存储 2 个卡片对象 (get_cards)。之后我做了另一种方法,如果需要的话应该将另一张卡片添加到列表中。第二个代码块应该检查谁需要卡片,然后将随机卡片附加到该特定人员列表。

class Person:
    def __init__(self, name):
        self.name = name
        self.hand = []
        self.get_cards()

    def get_cards(self):
        for i in range(2):
            rand_card = random.choice(Deck.cards)
            self.hand.append(rand_card)
            Deck.cards.remove(rand_card)

    def get_add_card(self):
        self.hand.append(random.choice(Deck.cards))

need_card = True
while need_card:
    answer = input("Does anyone need a card? Yes or No")
    if answer.lower() == 'no':
        need_card = False
    elif answer.lower() == 'yes':
        player_need = input("Which player needs a card?").lower()
        Person(player_need).get_add_card()
        print (Person(player_need).hand)
    else:
        print("Please answer using yes or no")

代码应将随机卡附加到人员手牌列表中。然而,这并没有发生,当我尝试在最后打印出他们的手牌时,它只显示他们是两张牌,这是该人开始时使用的牌。

您的问题是每次执行 Person(need_player) 时,您都会创建一个单独的 Person 对象。即使您使用相同的 name,它也不是与以前相同的对象,并且它将有一个单独的列表作为其 hand 属性。

为避免一遍又一遍地重新创建播放器,您应该预先创建它们并将它们放入列表或字典中:

# up front, create the players (perhaps by prompting, but here hard-coded)
players = {"alice": Person("Alice"), "aob": Person("Bob")}

# later, you can look them up by name:
player_need = input("Which player needs a card?").lower()
players[player_need].get_add_card()
print(players[player_need]).hand)

您可能需要更多的逻辑来避免用户输入未知名称时出现错误,但这应该可以让您了解大致情况。