我写了一个简单的类:
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属性?你知道吗
非常感谢你帮助我!你知道吗
return
中断函数的控制流,并使它立即退出,返回传递给它的值,这就是为什么它会在第一次迭代时停止发布代码的原因。这正是预期的工作方式,请参阅^{在返回部分结果之前,您需要将其累积到某个位置,例如:
相关问题 更多 >
编程相关推荐