String representation of an object in Python
本问题已经有最佳答案,请猛点这里访问。
因此,在我目前用作参考的书(用算法和数据结构解决问题)中,这是如何实现图的。这里我不明白的是,类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | class Vertex: def __init__(self,key): self.id = key self.connectedTo = {} def addNeighbor(self,nbr,weight=0): self.connectedTo[nbr] = weight def __str__(self): return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) def getConnections(self): return self.connectedTo.keys() def getId(self): return self.id def getWeight(self,nbr): return self.connectedTo[nbr] class Graph: def __init__(self): self.vertList = {} self.numVertices = 0 def addVertex(self,key): self.numVertices = self.numVertices + 1 newVertex = Vertex(key) self.vertList[key] = newVertex return newVertex def getVertex(self,n): if n in self.vertList: return self.vertList[n] else: return None def __contains__(self,n): return n in self.vertList def addEdge(self,f,t,cost=0): if f not in self.vertList: nv = self.addVertex(f) if t not in self.vertList: nv = self.addVertex(t) self.vertList[f].addNeighbor(self.vertList[t], cost) def getVertices(self): return self.vertList.keys() def __iter__(self): return iter(self.vertList.values()) |
一行代码就足够问你问题了:
1 | str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) |
让我们把它分开:
我猜是3。给你带来问题。它只是一个中心的Python构造,选择
之后,您将得到一个字符串,
1 | print Vertex |
1 2 | g = Vertex(key) print str(g) # calls __str__ |
这可以实现以使打印对象更容易