# 7.6.实现

## 7.6.实现

``````class Vertex:
def __init__(self,key):
self.id = key
self.connectedTo = {}

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]``````

Listing 1

``````class Graph:
def __init__(self):
self.vertList = {}
self.numVertices = 0

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

if f not in self.vertList:
if t not in self.vertList:

def getVertices(self):
return self.vertList.keys()

def __iter__(self):
return iter(self.vertList.values())``````

Listing 2

``````>>> g = Graph()
>>> for i in range(6):
>>> g.vertList
>>> for v in g:
...    for w in v.getConnections():
...        print("( %s , %s )" % (v.getId(), w.getId()))
...
( 0 , 5 )
( 0 , 1 )
( 1 , 2 )
( 2 , 3 )
( 3 , 4 )
( 3 , 5 )
( 4 , 0 )
( 5 , 4 )
( 5 , 2 )``````

Figure 2