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

2024-10-02 06:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用boost::python做一些非常简单的事情。我可以找到类成员函数的文档,以及继承类的文档(bleurch),但我找不到公开通过组合创建的类层次结构的语法。在

<> p>所以我有一些C++代码,它的意思是:

struct A{
    double x,y;
};

struct B{
    A foo;
    double z;
};

我想公开这两个类,这样在python中我可以编写如下内容:

^{pr2}$

当然有可能吗?但我想不通。在

非常感谢!在

编辑:

虚惊一场。。。这是自动完成的;如果您使用以下导出代码分别导出每个文件:

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的技术细节我还不明白。。。欢迎进一步澄清。在


Tags: 函数代码文档列表foodefdir成员
1条回答
网友
1楼 · 发布于 2024-10-02 06:21:17

dir的文档说明:

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

在您的示例中,类成员作为实例属性而不是类属性导出,这是导出非静态类成员时需要的。这就是为什么您需要在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']

相关问题 更多 >

    热门问题