Python 对象保留以前的数据?

k9b*_*k9b 4 python oop initialization class

我见过这个问题的多个实例,例如这个,但它无法确定我到底做错了什么,因为我没有默认参数。

我究竟做错了什么?Python对象实例化保留先前实例化的数据?

#Table.py
class Table:

def __init__(self, players):
    self.deck = Deck()
Run Code Online (Sandbox Code Playgroud)

这是主要的

t = Table(2)
print len(t.deck.cards)

t = Table(2)
print len(t.deck.cards)
Run Code Online (Sandbox Code Playgroud)

我希望每次都能打印 48,但它却打印出来

48 and then 96
Run Code Online (Sandbox Code Playgroud)

为什么是这样?这个成员变量不应该每次都被覆盖吗?

#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)
Run Code Online (Sandbox Code Playgroud)

卡.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)
Run Code Online (Sandbox Code Playgroud)

gsa*_*ras 6

在构造函数中初始化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)
Run Code Online (Sandbox Code Playgroud)

这样,每次创建该类的新实例时,cards都会重新初始化。

您的方法没有按您希望的方式工作,因为cards是一个类数据成员,在 class 的所有实例之间共享Deck