[C++-sig] Re: deriving in python from a C++ base class
David Abrahams
dave at boost-consulting.com
Fri Jul 4 00:25:41 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.
>> Here is more information:
>> http://www.boost.org/libs/python/doc/PyConDC_2003/bpl.html#inheritance
>
> thanks, that works !
>
> I still have a question, though:
>
> The reason I missed that was that in my real code I initialized the
> class_<> with a no_init argument, as that was declared to be the way
> to make the (C++) class non-instantiable.
Passing no_init to the class_<...> doesn't affect the C++ class'
instantiability; it only affects the instantiability of the
corresponding Python class.
> However, even though I only want subclasses to be instantiated, I of
> course do need to initialize the base class (i.e. run its
> constructor).
>
> How should I do that, then ?
I'm afraid there's no good way to impose that restriction yet. As a
matter of fact, no_init should be more sophisticated and raise an
exception only when the Python class of the "self" argument is an
exact match for the wrapped class (not a subclass). Maybe you'd like
to contribute the code for that?
Note, however, that it still wouldn't be a very useful check, since
there's nothing to prevent:
>>> class Foo(WrappedClass):
... pass
...
>>> x = Foo()
Foo is essentially identical to WrappedClass, so what have you
enforced by preventing:
>>> x = WrappedClass
??
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list