[C++-sig] Re: Deriving classes
David Abrahams
dave at boost-consulting.com
Sun Sep 14 00:27:49 CEST 2003
yakumoklesk at yahoo.es writes:
> It is possible to derive a C++ class from a python class?
Not really.
> The dynamism of python respect the static methods of C++ for
> declaring classes makes me think it won't be possible.
>
> Anyway, what I want is to derive from de top class object from
> python, to take advantage of the use of slots.
Boost.Python extension classes *are* derived from object, so you
*should* be able to use slots with Python classes derived from
Boost.Python C++ classes...
...argh! That won't work because of the fact that we're using the
variable-length part of the Python object to help us store C++ objects
directly in the Python instance instead of using a separate dynamic
allocation. Python won't let you add slots to subclasses of types
with a tp_itemsize. Well, this is just another piece of evidence
that in-place storage was a poorly-chosen optimzation. One day we're
going to remove it and you'll be able to add slots in subclasses.
> Can I make it using boost.python or had I to derive from the C++
> class in the python source code?
Well, what you can do is something like the following:
void method1(object self, int x);
std::string method2(object self, char const*);
object make_derived_class(object base_class)
{
// get the metaclass object
object metaclass = base_class.attr("__class__");
// populate method dict
dict d;
d["method1"] = method1;
d["method2"] = method2;
// call the metaclass to produce a derived class
return metaclass("derived", make_tuple(base_class), d);
}
If you wrap make_derived_class you can then do:
>>> DerivedWithSlots = make_derived_class(MyClassWithSlots)
Now you have a new Python class with some wrapped C++ functions for
methods.
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list