Reputation: 45
I'm having trouble understanding how methods work when creating a class of my own.
this is my class method:
def compare_coll(self,coll_1, coll_2) -> None:
''' compares two collections of key words which are dictionaries,
<coll_1> and <coll_2>, and removes from both collections every word
that appears in both collection'''
overlap = set(coll_1).intersection(set(coll_2))
for key in overlap:
del coll_1[key], coll_2[key]
My class 'Collection_of_word_counts' has one instance variable, called 'counts' which stores a dictionary where the keys are words and the values are their number of occurrences. the initializer will read in the words from a txt file, and store them in self.counts.
I don't know how to use this method. I know that I implemented it correctly.
>>> c1.compare_coll(c2)
produces:
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
builtins.TypeError: compare_coll() missing 1 required positional argument: 'coll_2'
and
>>> Collection_of_word_counts.compare_coll(c1,c2)
produced the same error.
I'm not exactly sure how to use this in the shell.
Upvotes: 0
Views: 181
Reputation: 122032
Your compare_coll
method is an instance method, not a class method. The first argument to an instance method, called self
by convention, is always the instance of the class the method is being called from (e.g. self == c1
for c1.compare_coll(c2)
), so you only need to provide one other argument. Try:
def compare_coll(self, other) -> None:
overlap = set(self.counts).intersection(set(other.counts))
for key in overlap:
del self.counts[key], other.counts[key]
This will work for either c1.compare_coll(c2)
or Collection_of_word_counts.compare_coll(c1, c2)
.
Note that I have referenced counts
directly for each of the two instances within the method.
Upvotes: 1