【发布时间】:2018-11-29 18:25:56
【问题描述】:
简单的文字编辑
代码:
class temp:
attr1 = 0
attr2 = []
t1 = temp()
t2 = temp()
t1.attr1 = 50
t1.attr2.append(50)
print(t1.attr1)
print(t1.attr2)
print(t2.attr1)
print(t2.attr2)
输出:
50
[50]
0
[50]
我只在attr2 对象t1 上调用了append,但append 更改了两个对象的attr2。如果attr2 是共享的(类属性),那么为什么attr1 的值对于t1 和t2 是不同的。什么可能导致了这种意外行为?
老问题
我正在为二十一点编写 Python 代码。我写的代码如下。
from random import randint
from IPython.display import clear_output
deck = ["S","D","C","H"]
class Player:
cards = []
total = 0
amount = 0
def __init__(self,money=0):
self.amount = money
def busted(self):
return self.total > 21
def showCards(self):
for i in self.cards:
print("| {}{} |".format(i%13,deck[i//13]),end = " ")
print()
def hit(self):
no = randint(1,53)
self.cards.append(no)
if no % 13 == 1:
if self.total + 11 > 21:
self.total+=1
else:
self.total+=11
else:
self.total += (no%13 if no%13 <= 10 else 10)
dealer = Player(10000)
p1 = Player(0)
print("Welcome to BlackJack ....")
while True:
try:
p1.amount = int(input("Enter the amount you currrently have for the game"))
except:
print("invalid Value")
continue
else:
break
Game = True
while Game:
print(dealer.cards)
print(p1.cards)
dealer.hit()
print(dealer.cards)
print(p1.cards)
print(dealer.total)
print(p1.total)
Game = False
这段代码的输出如下
Welcome to BlackJack ....
Enter the amount you currrently have for the game55
[]
[]
[45]
[45]
6
0
如您所见,我在dealer 对象上只调用了一次hit(),但它会将其附加到dealer 和p1 对象的cards 属性。但是total 属性不同。谁能解释导致这种意外行为的原因?
【问题讨论】:
-
代替卡片,试试 self.cards
-
具体在哪里定义?
-
在__init__()中,添加self.cards = []
-
是的,它成功了。但这并不能解释为什么
total不同而cards相同 -
您只添加到一个玩家,即,dealer.hit() 将数量添加到经销商实例而不是玩家实例。
标签: python python-3.x class object class-attributes