我有2類,A和B B,從A.用Cython和C++的繼承
//C++
class A
{
public:
int getA() {return this->a;};
A() {this->a = 42;}
private:
int a;
};
class B: public A
{
public:
B() {this->b = 111;};
int getB() {return this->b;};
private:
int b;
};
現在我想用用Cython接口這兩個類和必須調用木屐的可能性()方法繼承從A B實例:
a = PyA()
b = PyB()
assert a.getA() == b.getA()
目前我PYX文件看起來像這樣:
cdef extern from "Inherit.h" :
cdef cppclass A:
int getA()
cdef cppclass B(A):
int getB()
cdef class PyA:
cdef A* thisptr
def __cinit__(self):
print "in A: allocating thisptr"
self.thisptr = new A()
def __dealloc__(self):
if self.thisptr:
print "in A: deallocating thisptr"
del self.thisptr
def getA(self):
return self.thisptr.getA()
cdef class PyB(PyA):
def __cinit__(self):
if self.thisptr:
print "in B: deallocating old A"
del self.thisptr
print "in B: creating new b"
self.thisptr = new B()
def __dealloc__(self):
if self.thisptr:
print "in B: deallocating thisptr"
del self.thisptr
self.thisptr = <A*>0
def getB(self):
return (<B*>self.thisptr).getB()
雖然我希望這個代碼爲n不要做任何太危險的事情,我也希望有更好的辦法來處理它。
而且使用模塊生成以下的輸出:
>>> from inherit import *
>>> b = PyB()
in A: allocating thisptr
in B: deallocating old A
in B: creating new b
>>> b.getA()
42
>>> b.getB()
111
>>> del b
in B: deallocating thisptr
而且我真的不喜歡分配的一個實例只是爲了後立即釋放它。
有關如何正確執行此操作的任何建議?
好吧,通過打開賞金,我正在尋找一種慣用的構造對於這種情況,你說你不知道Python和Cython,雖然你的答案可以修改爲合法的Python(和Cython)代碼,但這會給Python用戶造成翻譯崩潰的威力,這是我的觀點這比浪費內存分配要糟糕多了 – ascobol 2012-05-09 17:30:22
我的回覆太長了,請留言我的帖子的後半部分 – 2012-05-09 17:37:01
a)我認爲在Cython中只能有一個構造函數,就像在Python中一樣 b)then在每種方法中,我們需要檢查一個正確的初始化... c)可能這是C模塊中任意預定義值的可能。在PyA __ cinit__中,我們將檢查一個額外的參數,這個非平凡的值可以繞過分配。在這種情況下,用戶不能「意外」地使譯員崩潰。 – ascobol 2012-05-09 18:51:46