我正在尝试编写一个处理卡片的程序,我遇到的问题是,当我将卡片对象交给一个玩家时,所有玩家都会在他们的类属性“手”中接收该对象。
代码如下,任何帮助表示赞赏!如果我没有正确遵循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()
答案 0 :(得分:1)
问题来自您的__init__
Player对象,在您的方式中,hand
将在所有Player实例之间共享:如9.3.5. Class and Instance Variables
{{3}部分所示}}。快速修复应该是
def __init__(self,name,balance=100,hand=[]):
self.hand = []
self.name = name
self.balance = balance
self.hand.extend(hand)
顺便说一句,编写函数来向玩家添加卡片并不是一个好习惯,而应该是接收玩家对象的函数,如:
def plyr_geta_card(player):
card = random.choice(deck)
player.hand.append(card)
deck.remove(card)