Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Basically, you can't, without modifying the <code>Graph</code> and <code>BFSGraph</code> classes. If <code>Graph</code> refers <code>Vertex</code>, it refers to <code>Vertex</code>, and you can't make it refer to anything else without actually changing the code of <code>Graph</code>. That said, there are three ways to do something like this.</p> <p>The simplest solution is to make a derived version of <code>Graph</code> that overrides <code>addVertex</code> so it uses your new <code>Vertex</code> subclass. Then you use that new class instead of the original <code>Graph</code> and all is well.</p> <p>The second, sneakier, and riskier approach is to monkeypatch it:</p> <pre><code>import graph graph.Vertex = MyNewVertex </code></pre> <p>Now anything that tries to use the <code>Vertex</code> class in the <code>graph</code> module will actually use your class instead. This is risky, though, since you never know what it will do to other code that thought it was using the original <code>Vertex</code>. (It's still a good idea to name your class something different, otherwise it's going to be confusing to tell which one is being used.) Also, it can silently fail to work if another class imported <code>Vertex</code> before your monkeypatch took effect.</p> <p>If you're designing the whole codebase and you really need to do this a lot, the larger-scale solution is to parameterize the vertex as part of the class. This makes it easier to write your own derived classes that interoperate with each other. That is, you do something like:</p> <pre><code>class Graph(object): vertexClass = Vertex def addVertex(self, key): # ... newVert = self.vertexClass(key) # etc. # etc. </code></pre> <p>Then later if you need to you can do:</p> <pre><code>class MyVertex(Vertex): # blah class MyGraph(Graph): vertexClass = MyVertex </code></pre> <p>The idea is that you use a class variable so that the Graph class knows what class to use for its vertices. You can then easily make a derived class that just changes this variable, without having to rewrite all the actual method code (assuming you really did keep the API the same in your MyVertex class). This adds a layer of indirection and may be a bit overkill for small projects, but if you have a lot of interdependent classes it can be useful to do this to have them explicitly keep track of how they need to use each other.</p>
 

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