gpt4 book ai didi

python - 使用 boost.python,如何扩展类的 __dir__ 函数?

转载 作者:行者123 更新时间:2023-11-28 04:37:11 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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>()));

但是,这样做,使用对象本身的一个实例,我们得到一个无限循环,因为它只是重新绑定(bind)内部指针。如果我们尝试调用 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() 它们。

关于python - 使用 boost.python,如何扩展类的 __dir__ 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51076598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com