gpt4 book ai didi

python - 当只指定一个对象时,对象被添加到多个对象类属性

转载 作者:太空宇宙 更新时间:2023-11-04 05:02:42 25 4
gpt4 key购买 nike

<分区>

我正在尝试编写一个发牌程序,但我遇到了一个问题,即当我向一个玩家发牌时,所有玩家都会在他们的类属性“手牌”中收到该对象。

代码在下面,感谢任何帮助!如果我没有正确遵循 stackoverflow 缩进格式,我深表歉意。这是我第一次发布问题。

    import random

class Player(object):
def __init__(self,name,balance=100,hand=[]):
self.name = name
self.balance = balance
self.hand = hand

def reveal_all(self):
'''
This method prints out a player's hand.
'''
reveal = []
for x in self.hand:
reveal = reveal + [x.name]
print(reveal)

class Card(object):
def __init__(self,name,val):
self.name = name
self.val = val

card_ob1 = Card('2 of Hearts',2)
card_ob2 = Card('3 of Hearts',3)
card_ob3 = Card('4 of Hearts',4)
card_ob4 = Card('5 of Hearts',5)
card_ob5 = Card('6 of Hearts',6)
card_ob6 = Card('7 of Hearts',7)
card_ob7 = Card('8 of Hearts',8)
card_ob8 = Card('9 of Hearts',9)

deck = [card_ob1,card_ob2,card_ob3,card_ob4,card_ob5,card_ob6,card_ob7,card_ob8]

def plyr1_geta_card():
card = random.choice(deck)
player1obj.hand += [card]
deck.remove(card)

def dealer_geta_card():
card = random.choice(deck)
dealerobj.hand.append(card)
deck.remove(card)

player1obj = Player('Me',100)
dealerobj = Player('The House')

# Player 1 gets a card
plyr1_geta_card()

# The card is added to both the dealer and player hand attribute for some reason!
dealerobj.reveal_all()

player1obj.reveal_all()

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com