繁体   English   中英

如何使用boost :: python从派生类中获取所有类的attr名称?

[英]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类。

我google了很多,但没有找到任何东西。 看起来像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感觉的有趣挑战。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM