python - 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)。
解决方案
是的,与成员函数或函数的方式完全相同:)
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)
。
推荐阅读
- android - 如何隐藏所有 ExoPlayer2?
- javascript - 反应状态意外改变
- oracle - 从 oracle 数据库中提取整个模式到另一个(java)(自动化)
- mongodb - 如何在mongodb中加入两个集合
- ios - 如何检查更新是否可用 - Swift 4.2 iOS 12
- javascript - 错误:属性 'require' 的值为 null 或未定义,不是 IE 浏览器 11 中的 Function 对象
- python - spaCy语言模块未下载
- c# - 在这里,是我的剑道网格,我想在 excel 导出时显示 vendorNo 字段,但不在网格上
- javascript - 在 Jquery 中替换字符串
- javascript - 如何在首次加载时将事件加载到 FullCalendar 的日历中?