我是Python的新手,正在做一个二十一点游戏作为一个项目。
我有一个父类“参与者”和两个子类“ Player”和“经销商”。当我对玩家进行更改时,例如创建了多个“玩家”实例和一个“经销商”实例,例如,player1.add_card('Ace of Spades')
'Ace of Spades'
卡被添加到Participant
的所有子类别中。即'Ace of Spades'
将出现在发牌人,玩家1和玩家2中。
我可以通过在super()调用之后放置self.hand = hand
来解决此问题(如Dealer()
类中的注释所示)...但是我想知道这是否是正确的选择,为什么即使我特地将同一张卡片添加到所有参与者实例中,也将其添加到所有参与者实例中?
我已经在下面发布了我的代码(删除了所有其他类属性)。
class Participant:
def __init__(self,name='',hand=[],val_hand=0,tot_funds=0,bet=0,move=''):
self.name = name
self.hand = hand
def add_card(self, new_card):
self.hand.append(new_card)
print(f"{new_card} was added to {self.name}'s hand")
class Player(Participant):
def __init__(self,name):
super(Player, self).__init__()
self.name = name
class Dealer(Participant):
def __init__(self):
super(Dealer, self).__init__()
self.name = 'Dealer'
# self.hand = []
if __name__ == '__main__':
player1 = Player('Tom')
player2 = Player('Jess')
dealer = Dealer()
player1.add_card('Ace of Spaces')
打印输出:
>>> print(player1.hand)
Ace of Spaces
>>> print(player2.hand)
Ace of Spaces
>>> print(dealer.hand)
Ace of Spaces