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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值