Well, you can change the order of constructor definitions, the latter will have a higher priority. Here are my results:
class_<Foo>("Foo") .def(init<bool>()) .def(init<double>()) .def(init<int>()); Foo() # calls Foo() Foo(True) # calls Foo(int) Foo(1) # calls Foo(int) Foo(4.2) # calls Foo(double)
As you can see, this is not an ideal solution. Therefore, if you really need to do work with overloaded constructors, I suggest you run your own factory function.
using namespace boost::python; static boost::shared_ptr<Foo> makeFoo(const object& data) { boost::shared_ptr<Foo> obj; if (PyBool_Check(data.ptr())) { bool val = extract<bool>(data); obj.reset(new Foo(val)); } else if (PyFloat_Check(data.ptr())) { double val = extract<double>(data); obj.reset(new Foo(val)); } else { int val = extract<int>(data); obj.reset(new Foo(val)); } return obj; } class_<Foo>("Foo") .def("__init__", make_constructor(makeFoo));
And using makeFoo:
Foo()
By the way, docs on python.org can be somewhat useful.
source share