使用boost.python,如何扩展一个类';s__________函数?
我有一个导出到python的类,在纯python中,我可以通过以下方式轻松扩展dir函数:使用boost.python,如何扩展一个类';s__________函数?,python,c++,boost,boost-python,Python,C++,Boost,Boost Python,我有一个导出到python的类,在纯python中,我可以通过以下方式轻松扩展dir函数: def __dir__(self): attr = list(self.__attributesMap().keys()) return attr + dir(type(self)) 我在我的C++类中添加了一个DIR函数,但是问题是如何在C++中用Boosi.python? < p>获得代码< dir(类型(自已))/>代码的值,不幸的是,我认为这是不可能的。我们可以部分声明该类:
def __dir__(self):
attr = list(self.__attributesMap().keys())
return attr + dir(type(self))
<>我在我的C++类中添加了一个DIR函数,但是问题是如何在C++中用Boosi.python? < p>获得代码< dir(类型(自已))/>代码的值,不幸的是,我认为这是不可能的。我们可以部分声明该类:
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);
这门课的类型不是我们想要的。因此,您不能使用类本身(无限循环),也不能使用类型(不像我们在Python中使用的类型),剩下什么?您可能可以两次定义该类,并使用一个类为另一个类的dir提供数据,但这似乎是多余的。最好只是手动编写dir函数来硬编码类上的其他方法。你必须手动.For(.p>)。< /p>你也可以添加C++代码吗?不可以用C++来添加属性,这个类代表很多类型,每个属性都有不同的属性。这就是我要进入的,AWASY是一个无限循环来获取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>()));
>>> 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']