Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在python中,构造后的第二个对象有第一个对象';谁的数据?_Python_Python 3.x_Dictionary_Object_Memory Management - Fatal编程技术网

为什么在python中,构造后的第二个对象有第一个对象';谁的数据?

为什么在python中,构造后的第二个对象有第一个对象';谁的数据?,python,python-3.x,dictionary,object,memory-management,Python,Python 3.x,Dictionary,Object,Memory Management,我编写了一个python3分类器类,如下所示: class BayesPredictor: word_counts = {} def train(X, y): ... populates word_counts dictionary with data ... 当我第一次构造BayesPredictor对象时,word\u counts字典为空: predictor = BayesPredictor() print(predictor.word_counts)

我编写了一个python3分类器类,如下所示:

class BayesPredictor:
    word_counts = {}

    def train(X, y):
        ... populates word_counts dictionary with data ...
当我第一次构造
BayesPredictor
对象时,
word\u counts
字典为空:

predictor = BayesPredictor()
print(predictor.word_counts) # prints {}
但是,当我训练第一个对象,然后再次构造另一个对象时:

predictor.train(X, y) # here X and y are my training data

predictor2 = BayesPredictor()
print(predictor2.word_counts) # prints { 'goodies': 1, 'mat': 1, 'uve': 1, ... }
我看到第二个对象甚至在训练阶段之前就已经在
word\u counts
字典中有条目了


为什么会发生这种情况?

单词计数
是一个类属性,由
BayesPredictor的所有实例共享。如果您想为每个实例创建一个单独的
dict
,则需要为每个实例创建一个新的空
dict
,最好是在
\uuuuuu init\uuuu
中:

class BayesPredictor:
    def __init__(self):
        self.word_counts = {}

    ....

word\u counts
是一个类属性,由
BayesPredictor
的所有实例共享。如果您想为每个实例创建一个单独的
dict
,则需要为每个实例创建一个新的空
dict
,最好是在
\uuuuuu init\uuuu
中:

class BayesPredictor:
    def __init__(self):
        self.word_counts = {}

    ....

这是因为word_counts是一个类变量。这意味着类的所有实例都将共享此变量

您需要的是一个实例变量

您的代码可以这样修改:

class BayesPredictor:
    def __init__(self):
        self.word_counts = {}

    def train(X, y):
        ... populates word_counts dictionary with data ...

这是因为word_counts是一个类变量。这意味着类的所有实例都将共享此变量

您需要的是一个实例变量

您的代码可以这样修改:

class BayesPredictor:
    def __init__(self):
        self.word_counts = {}

    def train(X, y):
        ... populates word_counts dictionary with data ...