Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The right thing to do is to allow your <code>Graph</code> class to take a user-defined class as an argument, and use that to represent vertices. Your <code>graph</code> module can provide a suitable default.</p> <p>In <code>graph.py</code> (modules should begin with lowercase letters):</p> <pre><code>class Vertex(object): def __init__(self,key): self.id = key self.connectedTo = {} class Graph(object): def __init__(self, vertexclass=Vertex): self.vertList = {} self.numVertices = 0 self.vertexclass = vertexclass def addVertex(self,key): self.numVertices += 1 newVert = self.vertexclass(key) self.vertList[key] = newVert return newVert def getVertex(self,k): if k in self.vertList: return self.vertList[k] else: return None </code></pre> <p>The only change is that <code>Graph.__init__</code> has a parameter whose default value is the plain <code>Vertex</code> class, allowing you to pass a different class when you create the <code>Graph</code> instance. That class is saved, and you use that whenever <code>addVertex</code> is called to create a new vertex.</p> <p>Then, in another module or script where you want to use a custom vertex class:</p> <pre><code>#!/usr/bin/python import graph class MyVertex(graph.Vertex): def __init__(self,key): super(Vertex,self).__init__(key) # extensions for BFS self.predecessor = None self.dist = 0 self.color = 'w' # white, grey, and black class BFSGraph(Graph): def __init__(self): super(BFSGraph, self).__init__(MyVertex) def getColor(self,k): return self.getVertex(k).color def test(): g=BFSGraph() g.addVertex('a') g.getColor('a') </code></pre> <p>Your <code>BFSGraph.__init__</code>, when called, just calls its parent's <code>__init__</code> with the <code>graph.Vertex</code> subclass you want to use.</p> <p>This is not the only way to organize the code, but the key to remember is that your <code>Graph</code> class (or any subclass derived from it) should document exactly the behavior the class implementing the vertex needs to implement.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload