I have a Base
and a Derived
class in C++ for which I create Python-bindings with pybind11
. The base class implements a function (__repr__
) in which I want to access the runtime type name of self
. However, the way I do it, it just provides me the base type:
class Base {};
class Derived : public Base {};
PYBIND11_MODULE(mwe, m) {
py::class_<Base>(m, "Base")
.def("__repr__", [](const Base& self) {
// want to see the runtime type (i.e. most derived)
// of the `self` object!
return py::type::of(py::cast(self)).attr("__name__");
});
py::class_<Derived, Base>(m, "Derived")
.def(py::init<>());
}
In Python:
from mwe import Base, Derived
print(Derived()) # returns "Base", not "Derived"
How would I access the runtime type of self
instead?