假设我有以下C++类:
class Animal {
public:
virtual void sound() = 0;
};
class Dog : public Animal {
public:
void sound() override {
std::cout << "Woof\n";
}
};
class Cat : public Animal {
public:
void sound() override {
std::cout << "Miao\n";
}
};
std::unique_ptr<Animal> animalFactory(std::string_view type) {
if (type == "Dog") {
return std::make_unique<Dog>();
} else {
return std::make_unique<Cat>();
}
}
是否有可能,如果有,如何使用Pybind11编写绑定,以便我在Python代码中可以编写:
dog = animalFactory('dog')
cat = animalFactory('cat')
dog.sound()
cat.sound()
并在派生类中调用正确的函数?
1条答案
按热度按时间rggaifut1#
我建议阅读这里的文档:https://pybind11.readthedocs.io/en/stable/advanced/classes.html
注意,在我的例子中,你需要用python写以下代码: