【问题标题】:using boost.python, how to extend a class's __dir__ function?使用 boost.python,如何扩展类的 __dir__ 函数?
【发布时间】:2018-06-28 07:02:42
【问题描述】:

我有一个导出到python的类,在纯python中,我可以很容易地通过这个扩展dir函数:

 def __dir__(self):
    attr = list(self.__attributesMap().keys())
    return attr + dir(type(self))

所以我在我的 c++ 类中添加了一个 dir 函数,但问题是如何使用 boost.python 在 c++ 中获取 dir(type(self)) 的值?

【问题讨论】:

  • 可以加c++代码吗?
  • 不能用c++添加属性,这个类代表了很多类型,每个类型都有不同的属性。

标签: python c++ boost boost-python


【解决方案1】:

不幸的是,我认为这是不可能的。我们可以部分声明这个类:

struct test {
    void foo() { printf("foo!\n"); }
    void bar() { printf("bar!\n"); }
    void baz() {}
};

// define initial tclass
auto tclass = class_<test>("test")
    .def("foo", &test::foo)
    .def("bar", &test::bar);

然后扩展dir函数:

auto cur = tclass();
tclass.def("__dir__",
    make_function(
        [cur] (object) -> object {
            list curdir = (list)object(handle<>(PyObject_Dir(cur.ptr())));
            curdir.append("hello");
            return curdir;
        },
        default_call_policies(),
        boost::mpl::vector<object, object>()));

但是,这样做,使用对象本身的实例,我们会得到一个无限循环,因为它只是重新绑定内部指针。如果我们尝试调用 PyObject_Type 并在其上调用 PyObject_Dir ,我们将得到 Boost.Python.class ,因为它是 boost::python 公开类的实际类型,并且它没有添加正确的对象(因为这是动态完成的)。

如果我们在 python 中查看,我们可以看到这一点:

>>> dir(skunk.test)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__instance_size__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo']

>>> dir(type(skunk.test))
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__weakrefoffset__', 'mro']

类的类型不是我们想要的。所以你不能使用类本身(无限循环),也不能使用类型(不是我们在 Python 中习惯的类型),还剩下什么?您可能可以定义该类两次并使用一个来提供另一个的目录,但这似乎是多余的。最好手动编写 dir 函数来硬编码类上的其他方法。无论如何,你必须手动 .def() 它们。

【讨论】:

  • 这就是我要进入的,总是一个无限循环来获取 dir 函数的结果。看来我必须找到另一种方法来做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
相关资源
最近更新 更多