pybind11使用教程笔记__3_C++类继承

1. C++类继承(非多态)

Inheritance and automatic downcasting
Suppose now that the example consists of two data structures with an inheritance relationship:

C++ 继承关系

struct Pet {
    Pet(const std::string &name) : name(name) { }
    std::string name;
};

struct Dog : Pet {
    Dog(const std::string &name) : Pet(name) { }
    std::string bark() const { return "woof!"; }
};

多态binding:两种方法

There are two different ways of indicating a hierarchical relationship to pybind11:
the first specifies the C++ base class as an extra template parameter of the py::class_:

方法1:C++ base class

py::class_<Pet>(m, "Pet")
   .def(py::init<const std::string &>())
   .def_readwrite("name", &Pet::name);


// Method 1: template parameter:
py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
    .def(py::init<const std::string &>())
    .def("bark", &Dog::bark);

方法2:python base class

Alternatively, we can also assign a name to the previously bound Pet class_ object and reference it when binding the Dog class:

py::class_<Pet> pet(m, "Pet");
pet.def(py::init<const std::string &>())
   .def_readwrite("name", &Pet::name);


// Method 2: pass parent class_ object:
py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
    .def(py::init<const std::string &>())
    .def("bark", &Dog::bark);

两种方法等效

Functionality-wise, both approaches are equivalent. Afterwards, instances will expose fields and methods of both types:

>>> p = example.Dog('Molly')
>>> p.name
u'Molly'
>>> p.bark()
u'woof!'

2. C++类继承 (多态)

The C++ classes defined above are regular non-polymorphic types with an inheritance relationship
平时用到比较少,暂时搁置

ref:

https://pybind11.readthedocs.io/en/stable/classes.html#inheritance-and-automatic-downcasting


版权声明:本文为weixin_41521681原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。