1

If in C++ a class had an overloaded constructor:

class MyClass {
    std::string name;
public:
    MyClass(){};
    MyClass(std::string name_){ name = name_;}
};

how do I expose this to python? Can I use py::overload_cast and py::init together?

Currently I expose the first one:

PYBIND11_MODULE(ex_module, module_handle){
    module_handle.doc() = "ex class";

    py::class_<MyClass>(module_handle, "PyEx")
        .def(py::init<>())
        ;
}

(Note that I'm using C++20 and python >=3.10)

I want to be able to do:

new_obj = PyEx()
new_obj = PyEx("blah")

Currently, PyEx("blah") isn't throwing any errors, but it's also not really passing blah into the C++ constructor. I check this by adding a print statement in the second constructor.

Edit: simplified the question.

3
  • 1
    Don't think that error has anything to do with Pybind11. You defined the constructor of Ex to take a single argument keyword_arg... then in the call Ex("blah", keyword_arg="foo") assign it two different values -- first the positional "blah", second the named "foo". Commented Oct 16, 2023 at 17:10
  • @DanMašek Sure, but then how can I overload the constructor and also have keyword arguments on the python side? Ok maybe I can simplify the question. edit: I simplified the question because I was convoluting two separate issues. Commented Oct 16, 2023 at 17:28
  • 2
    The documentation says "To define multiple overloaded constructors, simply declare one after the other using the .def(py::init<...>()) syntax." Have you tried that? Commented Oct 16, 2023 at 17:49

1 Answer 1

2

There is no need to use any overload_cast tricks, because exposing the constructor is different than exposing a method where you pass the pointer to member function. You just need to define your single argument constructor after (or before) the default one:

    py::class_<MyClass>(module_handle, "PyEx")
        .def(py::init<>())
        .def(py::init<std::string>())
        ;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.