我已經看到這個問題的多個實例像這樣,但它沒有確定我做錯了什麼,因爲我沒有默認參數。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