Cython中的默认参数值继承了类方法

时间:2017-12-29 19:40:29

标签: python cython default-value subclassing multiple-files

我正在尝试为d方法的参数FunctionA.evaluate添加默认值,但我收到Signature not compatible with previous declaration'Function' is not a type name编译错误。如何正确地做到这一点?整个项目位于my Github

由于我是Python和Cython的新手,我还要感谢关于下面代码的任何其他评论(甚至语法相关)。

目标是让这个简单的测试通过:

test_ti.py

from ti import SubclassA, SubclassB
import pytest

def test_run_me():

    this_A = SubclassA(a=1, b=2)
    ret_A = this_A.do_that(c=3)  # Throws: TypeError: do_that() takes exactly 2 positional arguments (1 given)
    assert(ret_A == 6)

    this_B = SubclassB(a=1, b=2)
    ret_B = this_B.do_that(c=3, d=4)
    assert(ret_B == 10)

项目的其余部分'骨架':

superclass.pxd

cdef class Superclass:

    cdef int a
    cdef int b
    cdef int c
    cdef int d

    cdef Function f

    cpdef int do_that(self, int c, int d) except? -1


cdef class Function:

    cpdef int evaluate(self, int a, int b, int c, int d) except *

superclass.pyx

cdef class Superclass:

    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.c = 0


    cpdef int do_that(self, int c, int d) except? -1:
        self.c = c
        self.d = d
        return(self.f.evaluate(self.a, self.b, self.c, self.d))


cdef class Function:

    cpdef int evaluate(self, int a, int b, int c, int d) except *:
        return 0

subclas_a.pyx

cimport superclass
from superclass cimport Superclass, Function


cdef class SubclassA(Superclass):

    def __init__(self, a=0, b=0):
        super(SubclassA, self).__init__(a=a, b=b)
        self.f = FunctionA()


cdef class FunctionA(Function):

    cpdef int evaluate(self, int a, int b, int c, int d) except *:
        # This function needs only 3 parameters, a, b and c and I would
        # love to have a d=0 default value here.
        return(a + b + c)

subclass_b.pyx

cimport superclass
from superclass cimport Superclass, Function


cdef class SubclassB(Superclass):

    def __init__(self, a=0, b=0):
        super(SubclassB, self).__init__(a=a, b=b)
        self.f = FunctionB()


cdef class FunctionB(Function):

    cpdef int evaluate(self, int a, int b, int c, int d) except *:
        return(a + b + c + d)

0 个答案:

没有答案