这就是我的Characters
类的使用方式。
Python控制台:
>>> chars = Characters()
>>> chars.add(Character("Link", "Zelda"))
>>> chars.add(Enemy("Goomba", "SMB"))
>>> chars.add(Enemy("Koopa", "SMB"))
>>> chars.games()
['Zelda' 'SMB']
>>> chars.characters("SMB")
['Koopa', 'Goomba']
如何使str(chars)返回以下内容:
"Zelda:
Link from Zelda
SMB:
The Fearsome Koopa from SMB
The Fearsome Goomba from SMB"
我的尝试 代码:
class Character(object):
def __init__(self, name, game):
self.name = name
self.game = game
def __str__(self):
return "{0} from {1}".format(self.name, self.game)
def __repr__(self):
return "Character('{0}','{1}')".format(self.name, self.game)
class Enemy(Character):
def __str__(self):
return "The Fearsome {0} from {1}".format(self.name, self.game)
class Characters():
def __init__(self):
self.g = []
self.c = {}
self.p = {}
def games(self):
return (self.g)
def characters(self, char_name):
if char_name not in self.c:
return []
return self.c[char_name]
def __str__(self):
s = ""
if not self.p:
return s
for x in self.p:
s+=x+":"
for y in self.p[x]:
s+=" "+y+" "
return s
def add(self, obj):
if not obj.game in self.g:
self.g.append(obj.game)
if not obj.game in self.c:
self.c[obj.game] = [obj.name]
self.p[obj.game] = [str(obj)]
else:
self.c[obj.game] += [obj.name]
self.p[obj.game] += [str(obj)]
答案 0 :(得分:0)
要在字符串中插入新行,请使用"\n"
。
所以,这应该起作用:
def __str__(self):
s = ""
for x in self.p:
s += x + ":\n\n"
for y in self.p[x]:
s += y + "\n\n"
return s
[注意:您不需要if not self.p:
行,因为如果self.p
为空,则for循环将不会执行。
还有其他方法可以做到这一点。
一种方法是在列表理解中使用join()
和dict.items()
。
尝试一下:
def __str__(self):
items = [
(p + ':\n\n' + '\n\n'.join(v))
for p, v in self.p.items()
]
return "\n\n".join(items)
注意:在Python版本2中,请改用dict.iteritems()
。