如何使用boost::p ython从派生类中获取所有类属性名称
How to get all class attr names from derived class using boost::python?
我想实现和使用一些类Base
。在Python中,它是这样的:
class Base:
def Enumerate(self):
d = []
for attr in dir(self):
if not attr.startswith('__') and not callable(getattr(self, attr)):
d.append(attr)
return d
class One(Base):
hello = "world"
class Two(Base):
foo = "bar"
arr = [One(), Two()]
arr[0].Enumerate()
arr[1].Enumerate()
但是我想使用 boost::python
在 C++ 中实现Base
类。
我用谷歌搜索了很多,但什么也没找到。看起来像与boost::python::wrapper
有关的东西.
有人可以指出如何做到这一点吗?
如果你不熟悉Boost.Python,那么本教程是一个很好的起点。 除此之外,参考是一个很好的资源,但需要一些经验,可能有点吓人或深奥。 此外,Boost.Python 并没有为整个 Python/C API 提供方便的功能,需要开发人员偶尔直接使用 Python/C API 编写代码。
这是一个完整的 Boost.Python 示例,注释中注明了 python 代码:
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
/// @brief dir() support for Boost.Python objects.
boost::python::object dir(boost::python::object object)
{
namespace python = boost::python;
python::handle<> handle(PyObject_Dir(object.ptr()));
return python::object(handle);
}
/// @brief callable() support for Boost.Python objects.
bool callable(boost::python::object object)
{
return 1 == PyCallable_Check(object.ptr());
}
class base {};
/// @brief Returns list of an object's non-special and non-callable
/// attributes.
boost::python::list enumerate(boost::python::object object)
{
namespace python = boost::python;
python::list attributes; // d = []
typedef python::stl_input_iterator<python::str> iterator_type;
for (iterator_type name(dir(object)), end; // for attr in dir(self):
name != end; ++name)
{
if (!name->startswith("__") // not attr.startswith('__')
&& !callable(object.attr(*name))) // not callable(getattr(self, attr))
attributes.append(*name); // d.append(attr)
}
return attributes; // return d
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<base>("Base")
.def("Enumerate", &enumerate)
;
}
及其用法:
>>> from example import Base
>>>
>>> class One(Base):
... hello = "world"
...
>>> class Two(Base):
... foo = "bar"
...
>>> arr = [One(), Two()]
>>>
>>> arr[0].Enumerate()
['hello']
>>> arr[1].Enumerate()
['foo']
尽管 Boost.Python 在提供 Python 和 C++ 之间的无缝互操作性方面做得很好,但如果可能的话,请考虑用 Python 而不是C++编写 Python。 虽然这是一个简单的例子,但该程序很少或根本没有用C++编写。 在更广泛的例子中,它可能需要关注非常微小的细节,这对保持 Pythonic 的感觉提出了一个有趣的挑战。
相关文章:
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 如何将类的属性从 c++ 获取到 QML 中
- 我想获取点的属性,它报告错误 C3867:"point::output_x":非标准语法;使用"&"创建指向成员的指针
- 如何使用C++获取/设置OBS中的垂直滚动过滤器属性?
- 如何在提升图形库中获取属性的类型
- 获取正在运行的程序的属性
- 使用setW()函数保存文件时,如何获取每个属性的值
- 如何在Qt中解析未知的xml并获取其中的所有属性
- 通过EventFilter到剪贴板获取QlineEdit的某些属性
- 如何在自定义操作DLL(MSI / Wix)中获取"INSTALLED"属性?
- 提升属性树:如何使用xml文件获取子树的子级
- C++,无法获取受保护的抽象类属性
- 使用 CDT 从头文件中获取属性定义的节点元素是什么
- 从元对象获取属性更改通知程序
- 按名称获取属性值
- QWebEngine:如何获取属性值
- c++使用链接从哈希表中获取属性
- 在libXML sax解析器(c++)中获取属性值的正确方法是什么?
- 如何在libxml2中获取属性并保存在c++的stl map中
- 如何通过脚本从Windbg中获取C++属性的地址