Python:设计_______________________________________
我在这里有一个类定义:Python:设计_______________________________________,python,coding-style,Python,Coding Style,我在这里有一个类定义: class Graph: def __init__(self,directional = False,simple=True,Filename=None): self.adjacencyList = {} self.directional = directional self.simple = simple 我为它设计了\uuuu str\uuu方法,如下所示: def __str__(self): sim
class Graph:
def __init__(self,directional = False,simple=True,Filename=None):
self.adjacencyList = {}
self.directional = directional
self.simple = simple
我为它设计了\uuuu str\uuu
方法,如下所示:
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
我发现它太冗长了,我在想也许有更干净的方法可以使用更少的代码行来完成它
你能给我一些建议吗?试试这个:
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)
改用:
该函数应该对您有所帮助。它将返回一个格式良好的字符串以供打印
>>> 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}
虽然与原始代码中的输出不完全相同,但我认为这是非常可读和接近的
然后,我会将您的整个\uuuu str\uuu
函数重写为:
def __str__(self):
return (
"Simple: {0.simple}\n"
"Directional: {0.directional}\n"
"{1}"
).format(self, pprint.pformat(self.adjacencyList))
这里不需要方括号。也许以前需要一些版本。@zch:See<代码>''.join()需要对项进行两次传递,使用生成器表达式会降低传递速度。如果更快,则使用列表理解。因此,不,从技术上讲,括号是不需要的,但无论如何都建议使用。
def __str__(self):
return (
"Simple: {0.simple}\n"
"Directional: {0.directional}\n"
"{1}"
).format(self, pprint.pformat(self.adjacencyList))