0

ここにクラス定義があります:

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

私はそれが非常に冗長であることがわかりました。おそらく、より少ないコード行を使用してそれを行うためのよりクリーンな方法があるのではないかと考えています.

いくつか提案をいただけますか?

4

3 に答える 3

4

代わりに文字列フォーマットを使用してください:

    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)
于 2013-01-11T18:38:52.043 に答える
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))
于 2013-01-11T18:46:19.850 に答える
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)
于 2013-01-11T18:37:31.967 に答える