2013-12-15 60 views
0

我有一个使用邻接表来跟踪顶点和边的图类,以及具有预定散列函数,看起来像下面的一个顶点类:从python的哈希中获取字典的关键?

class Vertex(): 
    def __init__(self, name): 
     self.name = name 
    def __hash__(self): 
     return hash(self.name) 

本质上说,在我的Graph类,我有一个名为addVertex的方法,它接受一个顶点对象并在添加它之前检查它是否存在于Graph中。如果它已经存在,我想返回已经在图中的对象,而不是我传入方法的参数。我将如何去实施这个?

class Graph(): 
    def __init__(self): 
     self.adjList = {} 

    def addVertex(vertex): 
     try: 
      self.adjList[vertex] 
      return ??????????? 
     except: 
      self.adjList[vertex] = {} 
      return vertex 

回答

1

只需使用一个成员测试:

if vertex in self.adjList: 

dict.__contains__的实施将自动使用__hash__特殊方法。

请注意,您Vertex类还必须实现一个__eq__平等方法:

class Vertex(): 
    def __init__(self, name): 
     self.name = name 
    def __hash__(self): 
     return hash(self.name) 
    def __eq__(self, other): 
     if not isinstance(other, type(self)): 
      return NotImplemented 
     return self.name == other.name 
+0

此外,后'Vertex'括号是多余的。 :P – iCodez

+0

当然,但我试图回应OP使用的风格,其中风格并不重要。 –