Python 对象保留以前的数据?

标签 python class oop initialization

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

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/

相关文章:

java - 静态方法不在主类中运行它

c# - 多播委托(delegate)和事件

php - 将参数添加到覆盖方法 E_STRICT 观察

c++ - 您如何调用位于类及其基类之间的接口(interface)?

PYTHON3.3 >> sybpydb.so : undefined symbol: PyUnicodeUCS2_Decode

c# - 如何在类中设置应用程序状态值?

python - 使用 2 种格式的 Python 更改类型列

java - Scala 相当于 Java java.lang.Class<T> 对象

python - 如何解决“未定义的 "Cannot read property '字段”

python - 执行 2 个样本 t 检验