Skip to content

Overriding virtual functions of abstract class in Python #848

Closed Answered by wjakob
huangweiwu asked this question in Q&A
Discussion options

You must be logged in to vote

This works fine for me:

class Dog {
public:
    virtual std::string bark() const = 0;
    virtual ~Dog() = default;
    std::string name;
};

struct PyDog : Dog {
    NB_TRAMPOLINE(Dog, 1);

    PyDog() { }
    std::string bark() const override {
        NB_OVERRIDE_PURE(bark);
    }
};

void myalarm(Dog *dog, size_t count = 3) {
    for (size_t i = 0; i < count; ++i)
        std::cout << dog->bark() << std::endl;
}

NB_MODULE(my_ext, m) {
    nb::class_<Dog, PyDog>(m, "Dog")
        .def(nb::init<>())
        .def("bark", &Dog::bark);
    m.def("alarm", &alarm, "dog"_a, "count"_a = 3);
}
import my_ext

class ShihTzu(my_ext.alarm.Dog):
    def __init__(self, name):
        super().__init__(…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@huangweiwu
Comment options

@wjakob
Comment options

Answer selected by huangweiwu
@huangweiwu
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants