繁体   English   中英

在 boost.python 中; 如何公开包含在另一个类中的类(通过组合)?

[英]In boost.python; how do I expose a class that is contained in another class (via composition)?

我想用 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 技术细节......欢迎进一步澄清。

dir 的文档说:

如果对象是类型或类对象,则列表包含其属性的名称,并递归地包含其基类的属性。

在您的示例中,您的类成员导出为实例属性,而不是导出非静态类成员时所需的类属性。 这就是为什么您需要在 python 中实例化类以使 dir 返回属性,因为在调用init方法之前这些属性不存在。

当声明类属性时,它们将在类型上调用 dir 时显示,因为类属性在类定义之后:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
...     name = "blah"
...     def __init__(self):
...         self.second_name = "blah2"
...
>>> dir(Foo)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'name']
>>> f = Foo()
>>> f
>>> dir(f)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'name', 'second_name']

暂无
暂无

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

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