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
It works fine when a single instance of WebText is created. But when multiple WebText instances are created, then the new variable seems to be shared by all the objects.
Well, yes; of course it would work fine with a single instance when all one of them is sharing the value. ;)
The value is shared because Python follows a very simple rule: the things you define inside the class
block belong to the class. I.e., they don't belong to instances. To attach something to an instance, you have to do it explicitly. This is normally done in __init__
, but in normal cases (i.e. if you haven't used __slots__
) can be done at any time. Assigning to an attribute of an object is just like assigning to an element of a list; there are no real protections because we're all mature adults here and are assumed to be responsible.
def __init__(self, text):
self.freq_dist_weighted = {}
# and proceed to modify it
Alternately:
def __init__(self, text):
freq_dist_weighted = {}
# prepare the dictionary contents first
self.freq_dist_weighted = freq_dist_weighted