我已经看到这个问题的多个实例像这样,但它没有确定我做错了什么,因为我没有默认参数。Python对象保持以前的数据?
What am I doing wrong? Python object instantiation keeping data from previous instantiation?
#Table.py
class Table:
def __init__(self, players):
self.deck = Deck()
这是主要
t = Table(2)
print len(t.deck.cards)
t = Table(2)
print len(t.deck.cards)
我希望它可以在每次打印48,而是它打印
48 and then 96
这是为什么?每次都不应该重写这个成员变量吗?
#Deck.py
from Card import *
import random
class Deck:
suits = ['H','C','D','S']
numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14]
cards = []
def __init__(self):
for num in self.numbers:
for suit in self.suits:
c = Card(num,suit)
self.cards.append(c);
random.shuffle(self.cards)
Card.py
class Card:
def __init__(self, num, suit):
self.num = num
self.suit = suit
def __repr__(self):
return str(self.num) + str(self.suit)
def __str__(self):
return str(self.num) + str(self.suit)
请张贴代码Deck.py – Penn
我猜你有一个叫'cards'在'Deck'类变量? – PRMoureu
新增@ Penn感谢:) – k9b