[C++-sig] Re: deriving in python from a C++ base class

David Abrahams dave at boost-consulting.com
Fri Jul 4 00:35:01 CEST 2003


Stefan Seefeld <seefeld at sympatico.ca> writes:

> Ralf W. Grosse-Kunstleve wrote:
>> --- Stefan Seefeld <seefeld at sympatico.ca> wrote:
>> 
>>>class MyWorld(World):
>>>     def __init__(self):
>>>         self.set('hi there')
>>>         print self.greet()
>> I think you have to call World.__init__() before you can use the
>> instance.
>
> playing more with the code, I'm observing the following:
>
> * instantiating 'MyWorld' in python will not call the World's constructor

Right.  Not calling the base __init__ is always an option in Python.

> * instantiating a 'MyWorld' object from within C++ will call the constructor

Huh?  MyWorld is a Python object.  How do you instantiate MyWorld from
within C++?  The only way I know how to do that is:

     void instantiate_myworld(myworld_class)
     {
         object myworld_object = myworld_class();
         ...
     }

And that will do exactly the same thing as:

    >>> MyWorld()

in Python.  No World::World() gets called.

> * adding a call to 'World.__init__(self)' into the definition of MyWorld.__init__
>    will call World's constructor twice, or, more generally, n + 1 times, if
>    n is the number of times I call World.__init__.

How?  Test case please?

> That seems to me quite error-prone and I'm wondering why it is done
> the way it is. 

What you're describing doesn't match any understanding I have of the
system, so I can't say yet.

> More than error-prone, I'm wondering how I could make it such that I
> can instantiate 'MyWorld' from python *and* C++, and still get the
> base constructor called once per instance in both cases.

Need clarification.

> Thanks,
> 		Stefan
>
> PS: by the way, I found the article you cite very useful, and I think that
>      it illustrates things that are not or less clearly documented in the
>      tutorial / reference. May be some of the text could be copied over...

Specific suggestions will certainly be considered.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list