在boost.python中;如何公开包含在另一个类中的类(通过组合)?
我想用 boost::python 做一些非常简单的事情。我可以找到类成员函数的文档以及继承类的文档,但我找不到用于公开通过组合创建的类层次结构的语法。
所以我有一些 C++ 代码,如下所示:
struct A{
double x,y;
};
struct B{
A foo;
double z;
};
我想公开这两个类,以便在 python 中我可以编写如下内容:
spam = A()
spam.x=1
spam.y=2
eggs = B()
eggs.foo=spam
eggs.z = 33
Print eggs.foo.y
当然可以吗?但我无法弄清楚。
非常感谢!
编辑:
误报......它是自动完成的;如果您使用以下导出代码单独导出每个:
class_<A>("A")
.def_readwrite("x",&A::x)
.def_readwrite("y",&A::y)
;
class_<B>("B")
.def_readwrite("z",&B::z)
.def_readwrite("foo",&B::foo)
;
让我困惑的是,您必须在子方法的完整列表通过 dir() 可见之前在 python 下实例化该类,即,以下会产生不同的结果,并且您必须使用第二种类型以获得完整的成员列表:
dir(B.foo)
dir(B().foo)
显然这里有一些我还不明白的Python技术细节......欢迎任何进一步的澄清。
I'd like to do something really simple with boost::python. I can find documentation for class member functions, and documention for inherited classes but nowhere can I find the syntax for exposing class hierarchies created via composition.
So I have some C++ code that goes something like this:
struct A{
double x,y;
};
struct B{
A foo;
double z;
};
And I want to expose both classes so that in python I can write something like:
spam = A()
spam.x=1
spam.y=2
eggs = B()
eggs.foo=spam
eggs.z = 33
Print eggs.foo.y
Surely that's possible? But I can't figure it out.
Many thanks!
EDIT:
False alarm... it's done automatically; if you use the following export code to export each individually:
class_<A>("A")
.def_readwrite("x",&A::x)
.def_readwrite("y",&A::y)
;
class_<B>("B")
.def_readwrite("z",&B::z)
.def_readwrite("foo",&B::foo)
;
What threw me is that you have to instantiate the class under python before the full list of submethods becomes visible with dir() i.e, the following produce different results, and you must use the second type to get a full member listing:
dir(B.foo)
dir(B().foo)
Evidently some python technicalities going on here which I don't yet understand... any further clarification welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
dir 的文档说:
在您的示例中,您的类成员被导出为实例属性,而不是类属性,这是导出非静态类成员时您想要的。这就是为什么您需要在 python 中实例化该类,以便 dir 返回属性,因为在调用 init 方法之前,属性并不存在。
声明类属性时,它们将在类型上调用 dir 时显示,因为类属性紧随类定义之后:
Documentation for dir says:
In your example, your class member are exported as instance attributes and not class attributes which is what you want when exporting non static class member. This is why you need to instantiate the class in python in order for dir to return the attributes because the attributes do not exist until the init method is called.
When declaring class attributes, they will show when calling dir on type because class attributes right after class definition: