簡體   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