0

我目前正在实现一个由 Numba@jitcalss装饰器包装的 Python 类。我的问题是关于编写递归方法。我知道也有将递归方法编写为迭代方法的方法,但就我而言,我相信递归的使用有助于我编写更可追溯的程序脚本。据我所知,Numba 不直接支持在 Numba 类中声明的递归方法。下面的代码没有直接呈现我的情况,但它相当于我的问题。当我运行代码时,Python 抛出的错误也在下面给出。欢迎任何形式的建议/改进/帮助

import numba


spec = []
@numba.experimental.jitclass(spec)
class basicClass(object):
    def __init__(self):
        pass

    def factorial(self,x):
        if x==1:
            return 1
        else:
            return x*self.factorial(x-1)

# MAIN BELOW
class_object = basicClass()
class_object.factorial(5)

错误如下:

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
- Resolution failure for literal arguments:
Failed in nopython mode pipeline (step: nopython frontend)
- Resolution failure for literal arguments:
Failed in nopython mode pipeline (step: nopython frontend)
compiler re-entrant to the same function signature
- Resolution failure for non-literal arguments:
None

During: resolving callee type: BoundFunction((<class 'numba.core.types.misc.ClassInstanceType'>, 'factorial') for instance.jitclass.basicClass#22839d9cf70<>)
During: typing of call at <ipython-input-7-ab7b9737001d> (16)


File "<ipython-input-7-ab7b9737001d>", line 16:
    def factorial(self,x):
        <source elided>
        else:
            return x*self.factorial(x-1)
            ^

- Resolution failure for non-literal arguments:
None

During: resolving callee type: BoundFunction((<class 'numba.core.types.misc.ClassInstanceType'>, 'factorial') for instance.jitclass.basicClass#22839d9cf70<>)
During: typing of call at <string> (3)


File "<string>", line 3:
4

1 回答 1

0

这是不支持的。该文档指出:

numba 中的递归支持目前仅限于带有显式类型注释的函数的自递归。此限制来自无法确定递归调用的返回类型。

问题是您不能指定函数的类型,因为它取决于包含函数的 self...

于 2022-01-30T22:17:45.820 回答