【发布时间】:2019-11-22 22:40:26
【问题描述】:
您好,我正在为黑杰克创建一个小测试脚本,在使用 OOP 时,我发现它为两个不同的实例返回相同的值
import random
color=['Hearts', 'Diamonds', 'Spades', 'Clubs']
shape=['Jack', 'Queen', 'King']
deck={}
for x in color:
for i in range(1,11):
commpination=str(i)+" "+x
deck[commpination] = i
for y in shape:
commpination=y+" "+x
deck[commpination] = 10
class Player:
def __init__(self,name='Dealer',money=0,bet=0,player_cards=[],player_value=0):
self.name=name
self.money=money
self.bet=bet
self.player_cards=player_cards
self.player_value=player_value
def hit(self):
global deck
#here will choose random card from the cards and add it to the player deck,
#will return Random key and put it in the new_card list
new_card=random.choice(list(deck.keys()))
#remove the choosen card from the deck
deck.pop(new_card)
self.player_cards.append(new_card)
ahmed=Player('Ahmed',200,20) # create new instance called Ahmed
sara=Player() # create new instance called Sara
ahmed.name # outputs 'Ahmed'
mohamed.name # outputs 'Dealer'
ahmed.hit() # run the method on ahmed
ahmed.player_cards # returns '5 Hearts'
mohamed.player_cards # returns '5 Hearts'
我的问题是,为什么 mohamed.player_cards 在没有首先运行 mohamed.hit() 的情况下返回 '5 Hearts' 并且我的脚本中的所有内容,每当我在第一个实例上运行方法时,我发现第二个实例也被修改了?
【问题讨论】: