[英]Implementing the __add__ Method in a Counter Class how?
我想在Counter類中實現add方法。 沒有導入Counter。
我有一個想法,如代碼中所見,但它總是給我一個錯誤。
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”類型的參數不可迭代
你的路線:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.