我在这里有一个课程定义:
class Graph:
def __init__(self,directional = False,simple=True,Filename=None):
self.adjacencyList = {}
self.directional = directional
self.simple = simple
我为此设计了__str__
方法:
def __str__(self):
simple = "Simple: "+ str(self.simple)+"\n"
directional = "Directional: " + str(self.directional)+"\n"
items = "{\n"
for vertex in self.adjacencyList.keys():
items = items +"\t"+str(vertex)+str(self.adjacencyList[vertex])+"\n"
items += "}"
string = simple + directional + items
return string
我发现它是如此冗长,我想也许有一些更简洁的方法可以使用更少的代码行来完成它。
你能给我一些建议吗?
答案 0 :(得分:4)
改为使用string formatting:
def __str__(self)
items = '\n'.join(['\t{0}{1}'.format(k, v)
for k, v in self.adjencyList.iteritems()])
return (
"Simple: {0.simple}\n"
"Directional: {0.directional}\n"
"{{\t{1}\n}}"
).format(self, items)
答案 1 :(得分:2)
pprint.pformat功能可以帮助您。它将返回一个格式良好的字符串,用于打印。
>>> import pprint
>>> adjacencyList = { 1: 100, 2: 200, 3: 300, 4: 400, 5: 500, 6: 600, 7: 700, 8: 800, 9: 900, 10: 1000 }
>>> s = pprint.pformat(adjacencyList)
>>> print s
{1: 100,
2: 200,
3: 300,
4: 400,
5: 500,
6: 600,
7: 700,
8: 800,
9: 900,
10: 1000}
虽然与原始代码中的输出不完全相同,但我认为这是非常易读和接近的。
然后我会将整个__str__
函数重写为:
def __str__(self):
return (
"Simple: {0.simple}\n"
"Directional: {0.directional}\n"
"{1}"
).format(self, pprint.pformat(self.adjacencyList))
答案 2 :(得分:1)
试试这个:
items = ''.join(['\t%s%s\n' % (k,v) for k,v in self.adjacencyList.items()])
return 'Simple: %s\nDirectional: %s\n{\n%s}' % (self.simple, self.directional, items)