Closed
Description
Note that this question combines two sections in the documentation:
- https://pybind11.readthedocs.io/en/stable/advanced/classes.html#overriding-virtual-functions-in-python
- https://pybind11.readthedocs.io/en/stable/classes.html#overloaded-methods
Consider this simple c++ class:
struct Loaded {
void func(int) { std::cout << "int\n"; }
void func(double) { std::cout << "double\n"; }
};
As explained in the documentation, one can create python bindings for this via:
PYBIND11_MODULE(pyfoo, m) {
py::class_<Loaded>(m, "Loaded")
.def(py::init<>())
.def("func", py::overload_cast<int>(&Loaded::func))
.def("func", py::overload_cast<double>(&Loaded::func));
And everything works perfectly on the python side.
>>> loaded = pyfoo.Loaded()
>>> loaded.func(10)
int
>>> loaded.func(10.0)
double
(It is a bit weird that one can do overloading in python via this).
Now consider another class:
class Listener {
public:
virtual ~Listener() = default;
virtual void func(int) = 0;
virtual void func(double) = 0;
};
As explained in the documentation, this requires us to setup a trampoline like this:
class PyListener : public Listener {
public:
void func(int i) override {
PYBIND11_OVERLOAD_PURE(void, Listener, func, i);
}
void func(double d) override {
PYBIND11_OVERLOAD_PURE(void, Listener, func, d);
}
};
PYBIND11_MODULE(pyfoo, m) {
py::class_<Listener, PyListener>(m, "Listener")
.def(py::init<>())
.def("func", py::overload_cast<int>(&Listener::func))
.def("func", py::overload_cast<double>(&Listener::func));
}
Now, my question is: How does one override these methods on the python side. Python clearly doesn't support overloading, so how can I write my own class in this case.
Failed attempt:
>>> import pyfoo
>>> class Listener(pyfoo.Listener):
... def func(self, n: int):
... print("int")
... def func(self, n: float):
... print("float")
...
>>> l = Listener()
>>> l.func(10)
float
Metadata
Metadata
Assignees
Labels
No labels