Skip to content

Adding bound methods at runtime #4311

Answered by ianhbell
ianhbell asked this question in Q&A
Discussion options

You must be logged in to vote

This link talks about it in detail for Python: https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance

With pybind11, the 0-th method doesn't work (py::cpp_function doesn't have the __get__ method), but the first method works for me. It's verbose, and unpleasant to work with, but most importantly, it functions properly.

Snippet:

// You cannot know at runtime what is contained in the model so you must iterate
// over possible model types and attach methods accordingly
void attach_model_specific_methods(py::object& obj){
    using namespace teqp::cppinterface;
    const auto& model = obj.cast<AbstractModel *>()->get_model();
    auto setattr = py::getattr(obj, "

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by ianhbell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant