You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pybind11中为C++类指定文档字符串(docstring)

给pybind11绑定的C++类添加文档字符串的方法

你可以通过两种方式为绑定的C++类设置文档字符串:

  • 构造函数传参(兼容所有pybind11版本)
    在初始化py::class_时,第三个参数就是类的文档字符串,这是最稳妥的写法:

    py::class_<Edge>(m, "Edge", "An Edge is used for representing an edge of a graph.")
        .def(py::init<int>());
    
  • .doc()方法(需pybind11 v2.4及以上版本)
    如果你的pybind11版本足够新,也可以用链式调用的.doc()方法直接设置文档字符串:

    py::class_<Edge>(m, "Edge")
        .doc("An Edge is used for representing an edge of a graph.")
        .def(py::init<int>());
    

你之前的代码报错,大概率是因为使用的pybind11版本不支持通过.doc()设置类文档,优先推荐构造函数传参的方式。

内容的提问来源于stack exchange,提问作者pnklein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:07:34