title: Passing a "pointer to a virtual function" as argument in Python
body: <p>Compare the following code in <strong>C++</strong>:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  struct A
  {
    virtual void bar(void) { std::cout &lt;&lt; "one" &lt;&lt; std::endl; }
  };
  
  struct B : public A
  {
    virtual void bar(void) { std::cout &lt;&lt; "two" &lt;&lt; std::endl; }
  };
  
  void test(std::vector&lt;A*&gt; objs, void (A::*fun)())
  {
    for (auto o = objs.begin(); o != objs.end(); ++o)
    {
      A* obj = (*o);
      (obj-&gt;*fun)();
    }
  }
  
  int main()
  {
    std::vector&lt;A*&gt; objs = {new A(), new B()};
  
    test(objs, &amp;A::bar);
  }
  </code></pre>
  
  <p>and in <strong>Python</strong>:</p>
  
  <pre><code>class A:
  
      def bar(self):
          print("one")
  
  
  class B(A):
  
      def bar(self):
          print("two")
  
  
  def test(objs, fun):
      for o in objs:
          fun(o)
  
  objs = [A(), B()]
  test(objs, A.bar)
  </code></pre>
  
  <p>The <strong>C++</strong> code will print:</p>
  
  <pre><code>one
  two
  </code></pre>
  
  <p>while the <strong>Python</strong> code will print </p>
  
  <pre><code>one
  one
  </code></pre>
  
  <p>How can I pass "a pointer to a method" and resolve it to the overridden one, achieving the same behavior in Python as in C++?</p>
  
  <p>To add some context and explain why I initially thought about this pattern. I have a tree consisting of nodes that can be subclassed. I would like to create a generic graph traversal function which takes a node of the graph as well as a function which might be overridden in subclasses of graph nodes. The function calculates some value for a node, given values calculated for adjacent nodes. The goal is to return a value calculated for the given node (which requires traversing the whole graph). </p>