在str类atribu中放置一个循环

2024-10-04 09:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个简单的类:

class MyDictionary:
def __init__(self):
    self.dictionary = {}

然后我填写我的辞典:

>>> fruit = MyDictionary()
>>> fruit.dictionary["apples"] = 13
>>> fruit.dictionary["cherrys"] = 12

然后,我希望当我写印刷品(水果)时,会出现这样的措辞:

I have 13 apples in my bag
I have 12 cherrys in my bag

所以我创建了一个简单的属性类:

def __str__(self):
    for key, value in self.dictionary.items():
        return "I have {} {} in my bag".format(value, key)

但这只返回第一行:

I have 13 apples in my bag

而且不打印樱桃线!为什么?如何将循环放入str属性?你知道吗

非常感谢你帮助我!你知道吗


Tags: keyinselfdictionary属性valuemydef
1条回答
网友
1楼 · 发布于 2024-10-04 09:26:05

return中断函数的控制流,并使它立即退出,返回传递给它的值,这就是为什么它会在第一次迭代时停止发布代码的原因。这正是预期的工作方式,请参阅^{} statement的文档。你知道吗

在返回部分结果之前,您需要将其累积到某个位置,例如:

def __str__(self):
    pieces = []
    for key, value in self.dictionary.items():
        pieces.append("I have {} {} in my bag".format(value, key))
    return "\n".join(pieces)

相关问题 更多 >