如何使用boost::p ython从派生类中获取所有类属性名称

How to get all class attr names from derived class using boost::python?

本文关键字:获取 属性 派生 boost 何使用 ython      更新时间:2023-10-16

我想实现和使用一些类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 的感觉提出了一个有趣的挑战。