为什么在python中,构造后的第二个对象有第一个对象';谁的数据?
我编写了一个python3分类器类,如下所示:为什么在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)
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 ...