我见过这个问题的多个实例,但它无法确定我到底做错了什么,因为我没有默认参数。
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)
卡片.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)
最佳答案
在构造函数中初始化cards
,像这样:
def __init__(self):
self.cards = []
for num in self.numbers:
for suit in self.suits:
c = Card(num,suit)
self.cards.append(c);
random.shuffle(self.cards)
这样,每次创建该类的新实例时,cards
都会重新初始化。
您的方法没有如您所愿,因为 cards
是一个类数据成员,在类 Deck
的所有实例中共享。
关于Python 对象保留以前的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46026613/