英文:
Cython: Overriding the `__cinit__` function with different parameters and signature
问题
我有兴趣对现有的Cython类(我们将其称为A
)进行子类化,该类具有如下__cinit__(self, int a, int b, *argv)
函数签名。
我的新类B
将具有如下__cinit__(self, int a, double c, *argv)
,其中不再需要或使用b
。
我想要类似以下的东西:
cdef class A:
cdef int a
cdef int b
def __cinit__(self, int a, int b, *argv):
self.a = a
self.b = b
cdef class B(A):
cdef double c
def __cinit__(self, int a, double c, *argv):
self.a = a
self.c = c
是否有方法可以实现这个?
英文:
I am interested in subclassing an existing Cython class (we'll call it A
), which has say the following __cinit__(self, int a, int b, *argv)
function signature.
My new class B
would have the following __cinit__(self, int a, int c, *argv)
, where b
is no longer required, or used.
I want something along the lines of:
cdef class A:
cdef int a
cdef int b
def __cinit__(self, int a, int b, *argv):
self.a = a
self.b = b
cdef class B(A):
cdef double c
def __cinit__(self, int a, double c, *argv):
self.a = a
self.c = c
Is there a way to do this?
答案1
得分: 1
No. It's not possible to do what you want.
The point of using __cinit__
rather than __init__
is that __cinit__
is always called. The way that Cython ensures this is that it takes control away from you by arranging the calls to the base classes itself.
If possible it'd be better to use __init__
instead of __cinit__
unless you need to "guarantee to be called" since this gives more flexibility.
Your best option is probably to use a staticmethod
factory function for class B
. But you do lose the guaranteed call of B.__cinit__
.
英文:
No. It's not possible to do what you want.
The point of using __cinit__
rather than __init__
is that __cinit__
is always called. The way that Cython ensures this is that it takes control away from you by arranging the calls to the base classes itself.
If possible it'd be better to use __init__
instead of __cinit__
unless you need to "guarantee to be called" since this gives more flexibility.
Your best option is probably to use a staticmethod
factory function for class B
. But you do lose the guaranteed call of B.__cinit__
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论