ajl123
ajl123

Reputation: 1272

Cython: Overriding the `__cinit__` function with different parameters and signature

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?

Upvotes: 0

Views: 96

Answers (1)

DavidW
DavidW

Reputation: 30916

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__.

Upvotes: 1

Related Questions