[C++-sig] Polymorphism between Python and C++

Patrick Hartling patrick at vrac.iastate.edu
Fri Nov 15 22:11:21 CET 2002


David Abrahams wrote:
> Patrick Hartling <patrick at vrac.iastate.edu> writes:
> 
> 
>>I'm doing some experimenting with Boost.Python v2, and I have run into
>>a problem I just can't seem to solve.  I want to define an abstract
>>base class in C++, derive a Python class from that base, and then use
>>the derived Python class polymorphically where the abstract C++ class
>>can be used.  I have attached the simplest code I could come up with
>>that demonstrates the problem.  When I run test.py, I get the
>>following output:
>>
>>I'm Derived1!
>>Traceback (most recent call last):
>>   File "./test.py", line 18, in ?
>>     handler.setObj(derived2)
>>TypeError: bad argument type for built-in operation
>>
>>I have been over the documentation (both on boost.org and on the
>>PythonInfo Wiki)
> 
> 
> Wow, I forgot about that Wiki. Is it worth linking
> http://www.python.org/cgi-bin/moinmoin/boost_2epython into the Boost
> web pages? Most of the info appears to be outdated...

I found it somewhat helpful.  There are a lot of pages that still need to 
be written, and I was careful to look at examples that were up to date 
with the V2 syntax.

>> but I can't figure out what I am doing wrong.  It
>>seems like I am close, but there must be some detail I'm missing.
> 
> 
> Yep. The detail is that Derived2.__init__() needs to call
> Base.__init__(). Otherwise there will be no C++ Base object in the
> Python object, and the conversion to Base* will fail.

Does that mean that I need to have a constructor in my Base class?  Since 
it is abstract, I didn't expect to have it get instantiated.  OTOH, I'm 
relatively new to Python, so maybe I am just misunderstading what I need 
to change.  If I just add Simple.Base.__init__() without modifying the 
C++, I get an error saying that Simple.Base cannot be instantiated from 
Python.

  -Patrick


-- 
Patrick L. Hartling                     | Research Assistant, VRAC
patrick at vrac.iastate.edu                | 2624 Howe Hall: 1.515.294.4916
http://www.137.org/patrick/             | http://www.vrac.iastate.edu/





More information about the Cplusplus-sig mailing list