2013-01-11 51 views
0

我有一个类定义在这里:的Python:更清洁的方式来设计__str__方法

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 

我发现它是如此冗长,我我想也许有一些更简洁的方法来使用更少的代码行。

你能给我一些建议吗?

回答

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) 
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

方括号是没有必要在这里。也许他们在某些版本之前需要。 – zch

+0

@zch:参见http://stackoverflow.com/a/9061024; '''.join()'需要两遍遍过这些项目,并且使用生成器表达式会减慢这一点。使用列表理解,而不是*更快*。所以,不,从技术上说不需要括号,但无论如何推荐。 –

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))