gpt4 book ai didi

python - 在子类中打印 python List

转载 作者:太空宇宙 更新时间:2023-11-03 14:51:29 25 4
gpt4 key购买 nike

我有一个父类(super class)如下:

class Container(object):
""" Holds hashable objects. Objects may occur 0 or more times """
def __init__(self):
""" Creates a new container with no objects in it. I.e., any object
occurs 0 times in self. """
self.vals = {}
def insert(self, e):
""" assumes e is hashable
Increases the number times e occurs in self by 1. """
try:
self.vals[e] += 1
except:
self.vals[e] = 1
def __str__(self):
s = ""
for i in sorted(self.vals.keys()):
if self.vals[i] != 0:
s += str(i)+":"+str(self.vals[i])+"\n"
return s

我在一个子类上工作:

class Bag(Container):
def remove(self, e):
""" assumes e is hashable
If e occurs in self, reduces the number of
times it occurs in self by 1. Otherwise does nothing. """
# write code here
if e in self.vals.keys():
self.vals[e] -= 1

def count(self, e):
""" assumes e is hashable
Returns the number of times e occurs in self. """
# write code here
if e not in self.vals.keys():
return 0
else:
return self.vals[e]

def __add__(self, other):
new_dict = other.vals
for e in self.vals.keys():
if e in other.vals.keys():
new_dict[e] += self.vals[e]
else:
new_dict[e] = self.vals[e]
return new_dict

def __str__(self):
s1 = ""
for i in sorted(self.new_dict.keys()):
s1 += str(i)+":"+str(self.new_dict[i])+"\n"
return s1

运行测试用例时:

  • a = 袋子()
  • a.insert(3)
  • a.insert(5)
  • b = 袋子()
  • b.插入(5)
  • b.插入(5)
  • b.插入(5)
  • 打印(a+b)

我的输出是:

{3:1, 5:4}

但是,预期的输出应该是:

3:1

5:4

如何获得正确格式的输出?非常感谢!

最佳答案

因为一旦你添加了 ab 你就不再有一个 Bag,只有一个普通的字典。

>>> type(a)
__main__.Bag
>>> type(b)
__main__.Bag
>>> type(a+b)
dict

如果你想添加 Bags 以返回另一个 Bag,你必须相应地修改你的 __add__ 函数,这样它返回一个 Bag 而不是 new_dict ,这只是一个普通的字典。

关于python - 在子类中打印 python List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45407240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com