Cython对象丰富的比较问题

时间:2017-06-22 17:39:38

标签: python cython

我一直试图解决Cython比较运算符的问题无济于事。浏览互联网一小时,但根本没有足够的文献清楚地解释如何使用丰富的比较。

基本上,我有两个以Frac(num_value,denom_value)形式的Cython Fractions对象,我想应用比较运算符。

这是我到目前为止设法解决的代码片段:

cdef class Fraction:

    cdef int _numerator, _denominator, numerator, denominator, a, b

    def __cinit__(self, numerator=0, denominator=None, bint _normalize=True):
        self._numerator = numerator
        self._denominator = denominator

def __richcmp__(a, b, int op):
    a, b = b, a
    if op == Py_EQ:
        return (<Fraction>a)._eq(b)
    elif op == Py_NE:
        result = (<Fraction>a)._eq(b)
        return NotImplemented if result is NotImplemented else not result
    elif op == Py_LT:
        pyop = operator.ge
    elif op == Py_GT:
        pyop = operator.le
    elif op == Py_LE:
        pyop = operator.gt
    elif op == Py_GE:
        pyop = operator.lt
    else:
        return NotImplemented
    return (<Fraction>a)._richcmp(b, pyop)

@cython.final   
def _eq(a, b):
    return (a._numerator == (<Fraction>b)._numerator and a._denominator == (<Fraction>b)._denominator)

@cython.final
cdef _richcmp(self, other, op):
    """Helper for comparison operators, for internal use only.
    Implement comparison between a Rational instance `self`, and
    either another Rational instance or a float `other`.  If
    `other` is not a Rational instance or a float, return
    NotImplemented. `op` should be one of the six standard
    comparison operators.
    """
    # convert other to a Rational instance where reasonable.
    if isinstance(other, (Fraction, Rational)):
        return op(self._numerator * other.denominator,
                  self._denominator * other.numerator)
    return NotImplemented

当我在两个分数对象上应用任何比较运算符时,即frac1&gt; frac2,我收到一个错误说:

  

TypeError:无法解决的类型:   _cython_magic_d905ad77d87531ef60e3cc8a19beacbf.Fraction()&lt; _cython_magic_bfbf1ca60faa3fc67aa19e16de034078.Fraction()

但是这个错误是完全无用的,我不知道这里究竟是什么导致问题。

现在,如果我做相同的运算符,则错误变为:

  

AttributeError:'_ cython_magic_bfbf1ca60faa3fc67aa19e16de034078.Fra'   对象没有属性'_eq'

略好一点,但我不知道为什么Cython无法识别_eq已经是Fraction对象中的一个属性。

0 个答案:

没有答案