Cython: 用不同的参数和签名重写`__cinit__`函数

huangapple go评论65阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月7日 04:05:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366046.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定