I have a C++ class like:
class Foo {
public:
Foo(int param1 = 0, int param2 = 1);
}
and I want to call it in python with keyword argument like below :
foo = Foo(arg1 = 1)
or
foo = Foo(arg2 = 5)
I don't know how to rename argument in constructor by boost::python , can anybody help me ? thank you in advance
To define the Python signature of your constructor with custom names and custom default values, you would export your class as follow:
boost::python::class_<Foo>(
"Foo",
boost::python::init<int, int>(
(boost::python::arg("self"), boost::python::arg("arg1")=0, boost::python::arg("arg2")=1)
)
);
Now from Python you would be able to do:
foo = Foo() # arg1 is 0, arg2 is 1
foo = Foo(1, 5) # arg1 is 1, arg2 is 5
foo = Foo(1) # arg1 is 1, arg2 is 1
foo = Foo(arg1=1) # arg1 is 1, arg2 is 1
foo = Foo(arg2=5) # arg1 is 0, arg2 is 5
Note: You do not have to declare the self
parameter, but it improves the docstring of your constructor:
Foo.__init__( (object)self [, (int)arg1=0 [, (int)arg2=1]]) -> None
Which is useful if you use a documentation generator such as Sphinx, etc.