據我所知,這是不可能不進行一些小的修改,以片斷1,或重新實現的boost::python::class_
部分。當boost::python::class_
類型的對象被實例化時,類型初始化和註冊發生在Boost.Python的內部。使用相同類型和參數實例化class_
將有效覆蓋前一個類對象。
在Python中,問題類似於被重新定義的類型。在下面的例子中,spam
標識用於一種類型,然後與不同的類型相關聯:
>>> class spam:
... def action1(self): pass
...
>>> # Redefines spam type.
... class spam:
... def action2(self): pass
...
>>> print hasattr(s, "action1")
False
>>> print hasattr(s, "action2")
True
而非spam
型經由其標識符擴展:
>>> class spam:
... def action1(self): pass
...
>>> # Extend spam type.
... def action2(s): pass
...
>>> spam.action2 = action2
>>> s = spam()
>>> print hasattr(s, "action1")
True
>>> print hasattr(s, "action2")
True
增壓。 Python示例與Python示例相當。在此片段中,spam
標識符被修改爲指向新類型,因爲實例化了新的class_
實例。
#include <boost/python.hpp>
class spam {};
void action1(spam& self) {}
void action2(spam& self) {}
BOOST_PYTHON_MODULE(example)
{
typedef boost::python::class_<spam> spam_class_type;
spam_class_type("spam")
.def("action1", &action1)
;
// Redefines spam type.
spam_class_type("spam")
.def("action2", &action1)
;
}
及其用法:
>>> import example
__main__:1: RuntimeWarning: to-Python converter for spam already
registered; second conversion method ignored.
>>> s = example.spam()
>>> print hasattr(s, "action1")
False
>>> print hasattr(s, "action2")
True
爲了擴展Boost.Python的類型,一個操作簡單的同時class_
實例:
#include <boost/python.hpp>
class spam {};
void action1(spam& self) {}
void action2(spam& self) {}
BOOST_PYTHON_MODULE(example)
{
typedef boost::python::class_<spam> spam_class_type;
spam_class_type spam_ = spam_class_type("spam");
spam_
.def("action1", &action1)
;
// Extend spam type.
spam_
.def("action2", &action2)
;
}
及其用法:
>>> import example
>>> s = example.spam()
>>> print hasattr(s, "action1")
True
>>> print hasattr(s, "action2")
True