2013-01-11 48 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))