Exposing simple polymorphism with boost python
Hi Python-Experts :-) i am starting to get really frustrated trying to expose a simple C++ polymorphism to python with boost::python. I do have the following structure in C++: struct Base { int typeID; }; struct Derived : public Base { int derivedProperty; } //and some more from base derived types.... Base *returnSomethingDerivedFromBase(...) { Derived *ret = new Derived; ret->derivedProperty = 1234; return ret; } BOOST_PYTHON_MODULE(foo) { class_<Base>("Base") .add_property("baseProperty", &Base::baseProperty); class_<Derived, bases<Base> >("Derived") .add_property("derivedProperty", &Derived::derivedProperty); def("returnSomethingDerivedFromBase", returnSomethingDerivedFromBase); } And in Python i just want to have the following: object = returnSomethingFromDerived() #object is of type Base if object.typeID = 1: #here i want to cast to Derived and access "derivedProperty" #but this is not working :-( : object.__class__ = Derived Is there a way to accomplish this at all? Or isn´t this possible as it would be in C++ ? Thanks a lot for your help!!
On 23/10/14 03:38 AM, Erik Türke wrote:
Hi Python-Experts :-)
i am starting to get really frustrated trying to expose a simple C++ polymorphism to python with boost::python. I do have the following structure in C++:
struct Base { int typeID; };
struct Derived : public Base { int derivedProperty; }
//and some more from base derived types....
Base *returnSomethingDerivedFromBase(...) { Derived *ret = new Derived; ret->derivedProperty = 1234; return ret; }
BOOST_PYTHON_MODULE(foo) { class_<Base>("Base") .add_property("baseProperty", &Base::baseProperty);
class_<Derived, bases<Base> >("Derived") .add_property("derivedProperty", &Derived::derivedProperty);
def("returnSomethingDerivedFromBase", returnSomethingDerivedFromBase); }
And in Python i just want to have the following:
object = returnSomethingFromDerived() #object is of type Base if object.typeID = 1:
Typo: you likely mean '==', not '='.
#here i want to cast to Derived and access "derivedProperty" #but this is not working :-( : object.__class__ = Derived
That's indeed not possible. But I also don't know why you want that. The objet presumably already is of type 'Derived', so there is nothing to cast. (In Python all attribute lookups happen at call-time.)
Is there a way to accomplish this at all? Or isn´t this possible as it would be in C++ ?
Both C++ and Python are strongly typed (i.e., all objects have a specific type, with specific methods bound to them). But contrary to C++, Python also is dynamically typed, so you can reassign a new object with a different type to an existing variable. In that context, casting isn't of any use. Or perhaps a more complete example would be useful to demonstrate your needs, so we can look into how best to support that in Python. HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin...
participants (2)
-
Erik Türke -
Stefan Seefeld