Python Pybind11-强制转换抽象继承类元素的列表

Python Pybind11-强制转换抽象继承类元素的列表,python,c++,pybind11,Python,C++,Pybind11,我有一个纯抽象类和两个继承类,其中每个类都包含一个名为go的方法,如下所示: //纯抽象类 类动物{ 公众: 虚拟std::string go()=0; }; //第一继承阶级 犬类:公共动物{ 公众: std::string go()重写{return“woof!”;} }; //第二继承阶级 猫类:公共动物{ 公众: std::string go()重写{return“meow!”;} }; 在Python端,定义了实例化对象(Dog或Cat)的列表。在C++方面,我试图编写一个函数 Ca

我有一个纯抽象类和两个继承类,其中每个类都包含一个名为
go
的方法,如下所示:

//纯抽象类
类动物{
公众:
虚拟std::string go()=0;
};
//第一继承阶级
犬类:公共动物{
公众:
std::string go()重写{return“woof!”;}
};
//第二继承阶级
猫类:公共动物{
公众:
std::string go()重写{return“meow!”;}
};
在Python端,定义了实例化对象(Dog或Cat)的列表。在C++方面,我试图编写一个函数<代码> CalqYOG/<代码>,它将这个Python列表作为输入,并调用列表中的每个对象的方法<代码> GO 。
导入测试
#定义对象列表(猫或狗)
动物=[]
append(test.Cat())
append(test.Dog())
append(test.Cat())
#尝试为给定列表的每个对象调用方法“go”
测试。呼叫(动物)
由于我事先不知道给定列表中每个元素的类型,因此我尝试编写函数
call\u go
,将元素转换为
Animal

void call\u go(py::列出动物){
用于(py::handle animal:animals){

std::cout编写
call\u go
的正确方法是

void call_go(py::list animals) {
  for (py::handle animal : animals) {
    // wrong 
    //std::cout << py::cast<Animal>(animal).go() << " ";
    // correct way
    std::cout << py::cast<Animal *>(animal)->go() << " ";
  }
}
void call\u go(py::列出动物){
用于(py::handle animal:动物){
//错
//标准::cout