首页 > 解决方案 > 如何在 Counter 类中实现 __add__ 方法?

问题描述

我想在 Counter 类中实现add方法。无需导入计数器。

我在代码中看到了一个想法,但它总是给我一个错误。

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 

这就是我要的

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

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

如果我尝试它的错误代码

TypeError:“MyCounter”类型的参数不可迭代

标签: pythonpython-3.x

解决方案


您的线路:

if x in args:

本质上是:

if x in MyCounter("hahhahahah"):

MyCounter不支持in运营商。

您可能想检查一下q

if x in args.q:

您还可in以为您的类实现运算符(使用该__contains__方法),或者dict直接从子类(这就是这样collections.Counter做的)。

您在这里也有同样的问题:

u=args.get(x)

MyCounter没有get()方法,你想用这个代替:

u=args.q.get(x)

推荐阅读