dictionary shared between objects for no reason?

后端 未结 4 1361
情书的邮戳
情书的邮戳 2021-01-22 18:59

The following code is supposed to create a new (modified) version of a frequency distribution (nltk.FreqDist). Both variables should then be the same length.

It works f

4条回答
  •  星月不相逢
    2021-01-22 19:51

    Your freq_dist_weighted dictionary is a class attribute, not an instance attribute. Therefore it is shared among all instances of the class. (self.freq_dist_weighted still refers to the class attribute; since there's no instance-specific attribute of that name, Python falls back to looking on the class.)

    To make it an instance attribute, set it in your class's __init__() method.

    def __init__(self, text):
        self.freq_dist_weighted = {}
        ...
    

提交回复
热议问题