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 回答