python - pybind : Is it possible to inform Python about the names of the arguments for constructors?

标签 python constructor anaconda spyder pybind11

在 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)。

最佳答案

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

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)

关于python - pybind : Is it possible to inform Python about the names of the arguments for constructors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51304635/

相关文章:

python - 用于时间序列预测的 LSTM 自动编码器

python - 喀拉斯 fit_generator : Unexpected usage of __getitem__ method

Python:初始化大量类成员的便捷方法

python - 如何运行 conda ?

python - 使用 TensorFlow 对实时视频进行分类

java - 传递一个字符串作为构造函数参数并获取 "illegal start of type"

java - 应用程序构造函数中的异常 - 无法启动类

c++ - 显式移动构造函数是否消除了隐式复制构造函数?

c++ - 在没有 Anaconda 的 Qt 版本的 Qt C++ 应用程序中包含 Anaconda python 3.6

python - 如何让 Keras 在 Anaconda 中使用 Tensorflow 后端?