简体   繁体   中英

Implementing the __add__ Method in a Counter Class how?

I want to implement the add method in the Counter class. Without importing Counter.

I kinda had an idea as seen in the code but it always gives me an Error.

class MyCounter:
    def __init__(self, s=None):
        self.q = {}
        for x in s:
            self.add(x)
    def __repr__(self):
        return str(self.q)
    def add (self,x):
        if x in self.q:
            self.q[x] = self.q[x] + 1
        else:
            self.q[x]=1
    def __add__(self, args):
        new_dict = self.q
        for x in new_dict:
            if x in args:
                u=args.get(x)
                new_dict[x] = new_dict[x]+ u
            else:
                new_dict[x]=1 

this is what i want

a= MyCounter("hahahahha")
a+ MyCounter("hahhahahah")

new_dict = {'h': 11, 'a': 8}

error code if i try it

TypeError: argument of type 'MyCounter' is not iterable

Your line:

if x in args:

Is essentially:

if x in MyCounter("hahhahahah"):

But MyCounter doesn't support the in operator.

You probably wanna check against the q instead:

if x in args.q:

You could also implement the in operator for your class (using the __contains__ method), or subclass from dict directly (this is what collections.Counter does).

You also have the same issue here:

u=args.get(x)

MyCounter doesn't have get() method, you wanna use this instead:

u=args.q.get(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM