首页 > 解决方案 > Pybind:是否可以告知 Python 构造函数的参数名称?

问题描述

在 Pybind 中,可以告知 Python函数参数的名称:

m.def("add", &add, "A function which adds two numbers",
  py::arg("i"), py::arg("j"));

http://pybind11.readthedocs.io/en/stable/basics.html#keyword-arguments

构造函数有类似的东西吗?Spyder (Anaconda) 默认已经显示函数的输入参数,但是对于构造函数,“帮助”只显示:(*args, **kwargs)。

标签: pythonconstructoranacondaspyderpybind11

解决方案


是的,与成员函数或函数的方式完全相同:)

struct Foo {
    Foo(int x, int y) {}
    void bar(int a, int b) {}
};

PYBIND11_MODULE(cpp_module, m) {
    py::class_<Foo>(m, "Foo")
        .def(py::init<int, int>(), py::arg("x"), py::arg("y"))
        .def("bar", &Foo::bar, py::arg("a"), py::arg("b"));
}

据我所知,使用py::arg函数、成员函数或构造函数之间没有真正的区别,它以相同的方式工作(包括默认值等)。


重载函数(包括构造函数)是一个有趣的案例。由于 Python 没有类似的重载机制,因此由 pybind11 处理。help()仍然可以工作,但它会显示如下内容:

__init__(...)
    __init__(*args, **kwargs)
    Overloaded function.

    1. __init__(self: some_cpp.Foo, x: int, y: int) -> None

    2. __init__(self: some_cpp.Foo) -> None

如您所见,__init__它本身需要(*args, **kwargs),这将是大多数 IDE 自动完成的。解决这个问题的一种方法是使用静态方法作为构造函数,这样你就可以给每个构造函数一个唯一的名字,这样 Python 就知道了。例如,Foo Foo::from_ints(int x, int y)Foo Foo::from_string(std::string s)


推荐阅读